所以我在linux(Ubuntu)中使用emacs文本编辑器编写了下面的代码,它基本上应该将传入的分隔符中的string分开。 当我运行它segfaulted我运行它通过GDB,它给了我一个错误在strcpy(我没有调用),但可能在sprintf隐式完成。 我没有想到我做了什么错误,所以我启动到Windows,并通过Visual Studio运行它,它工作正常,我是新的Linux编写C,并知道问题是在While循环,我打电话sprintf()(哪是奇怪的,因为在循环之外的调用写入而不会导致错误)将令牌写入数组。 如果有人能告诉我哪里出错,我将不胜感激。 这是代码
/* 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()
在循环的最后一次迭代中,您不会检查strtok
的返回NULL
是否为NULL
…所以strtok
可以返回NULL
,但是您仍然将token
的NULL
值传递给sprintf
。
改变你的while循环到以下内容:
while(token = strtok(NULL, delimiter)) sprintf(bigBuffer[++count], "%s", token);
这样,你永远不能传递一个NULL
指针给strtok
因为while循环的NULL
指针检查会强制这个token
在调用sprintf
时总是有一个有效的值。
你应该询问gdb的完整追溯你的程序崩溃的地方。 事实上,你不知道它在哪里崩溃意味着你没有要求它的完整回溯,这是重要的。