【发布时间】:2012-02-27 18:06:50
【问题描述】:
所以我使用 emacs 文本编辑器在 linux(Ubuntu) 中编写了以下代码,它基本上应该分割传入的分隔符上的字符串。当我运行它时,它出现了段错误,我通过 GDB 运行了它,它在 strcpy 处给了我一个错误(我不调用它),但可能在 sprintf 中隐式完成。我不认为我做错了什么,所以我启动到 Windows 并通过 Visual Studio 运行它,它工作正常我是在 Linux 中编写 C 的新手,并且知道问题出在我调用 sprintf() 的 While 循环中(很奇怪,因为循环外的调用写入而不会导致错误)将令牌写入数组。如果有人能告诉我哪里出错了,我将不胜感激。这是代码
/* split()
Description:
- takes a string and splits it into substrings "on" the
<delimeter>*/
void split(char *string, char *delimiter)
{
int i;
int count = 0;
char *token;
//large temporary buffer to over compensate for the fact that we have
//no idea how many arguments will be passed with a command
char *bigBuffer[25];
for(i = 0; i < 25; i++)
{
bigBuffer[i] = (char*)malloc(sizeof(char) * 50);
}
//get the first token and add it to <tokens>
token = strtok(string, delimiter);
sprintf(bigBuffer[0], "%s", token);
//while we have not encountered the end of the string keep
//splitting on the delimeter and adding to <bigBuffer>
while(token != NULL)
{
token = strtok(NULL, delimiter);
sprintf(bigBuffer[++count], "%s", token);
}
//for(i = 0; i < count; i++)
//printf("i = %d : %s\n", i, bigBuffer[i]);
for(i = 0; i< 25; i++)
{
free(bigBuffer[i]);
}
} //end split()
【问题讨论】:
-
您的问题不在于 linux 上的编译——而是您正在编写的程序崩溃。
标签: c linux pointers gcc ubuntu