strtok() returns 奇怪的值和段错误

strtok() returns weird values and segfault

我正在使用 strtok() 从文件中提取数据中的字符。

这是我的代码:

fgets(text, 12, myFile);

printf ("text is: %s \n", &text);
char *token;
token = strtok(text, " ");
printf("first token is: %s \n", &token);

printf ("text is: %s \n", &text);
token = strtok(NULL, " ");
printf("second token is: %s \n", &token);

输出如下:

text is: 4 3       //this is the expected and correct value of "text"
first token is:  ڱ[? 
text is: 4        // I was expecting this to be 3 after getting the first token...
second token is: "ڱ[? 
Segmentation fault: 11

因此如您所见,strtok() 不仅没有得到正确的值,而且似乎以一种非常奇怪的顺序遍历了文本。关于为什么会这样的任何想法?非常感谢您!

所有 printf 中的 %s 期望 char*。您传递 &text&token,它们都是 char**。这会调用 C11 标准中规定的未定义行为:

7.21.6.1 The fprintf function

[...]

  1. If a conversion specification is invalid, the behavior is undefined. 282 If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

要解决此问题,请删除所有 printf 中的 & 符号,即替换以下所有语句:

printf ("text is: %s \n", &text);
printf("first token is: %s \n", &token);
printf ("text is: %s \n", &text);
printf("second token is: %s \n", &token);

printf ("text is: %s \n", text);
printf("first token is: %s \n", token);
printf ("text is: %s \n", text);
printf("second token is: %s \n", token);