因此,我使用emacs文本编辑器在linux(Ubuntu)中编写了以下代码,它基本上应该在传入的分隔符上拆分字符串。当我运行它时,它是段错误的,但我通过GDB运行它,它在strcpy(我不调用)上给我一个错误,但可能是在sprintf中隐式完成的。我没想到我做错了什么,所以我启动了Windows并通过Visual Studio运行了它,并且工作正常,我是Linux编写C语言的新手,并且知道问题出在While循环中,我在其中调用sprintf()(之所以很奇怪,是因为循环外的调用在写入时不会引起错误)将 token 写入数组。如果有人能告诉我我要去哪里错了,我将不胜感激。这是代码
/* 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()
最佳答案
您不需要在循环的最后一次迭代中从NULL
的返回中检查strtok
,因此strtok
可以返回NULL
,但是您仍将NULL
指针中的token
值传递给sprintf
。
将while循环更改为以下内容:
while(token = strtok(NULL, delimiter)) sprintf(bigBuffer[++count], "%s", token);
这样,您就永远无法将
NULL
指针传递给strtok
,因为while循环NULL
-pointer检查将强制在将token
作为参数调用时sprintf
始终具有有效值。