为什么以下 C 程序会出现总线错误?
我认为这是第一个失败的 strtok 调用。好久没写C了,有点不知所措。非常感谢。
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv) {
char *str = "one|two|three";
char *tok = strtok(str, "|");
while (tok != NULL) {
printf("%s\n", tok);
tok = strtok(NULL, "|");
}
return 0;
}
I think it's the very first strtok call that's failing. It's been a while since I've written C and I'm at a loss. Thanks very much.
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv) {
char *str = "one|two|three";
char *tok = strtok(str, "|");
while (tok != NULL) {
printf("%s\n", tok);
tok = strtok(NULL, "|");
}
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
字符串文字应分配给 const char*,因为修改它们是未定义的行为。我很确定 strtok 修改了它的参数,这可以解释你看到的不好的事情。
String literals should be assigned to a const char*, as modifying them is undefined behaviour. I'm pretty sure that strtok modifies it's argument, which would explain the bad things that you see.
有 2 个问题:
将
str
设为char[]
类型。 GCC 给出警告foo.cpp:5: warning: deprecated conversion from string Constant to 'char*'
这表明这是一个有问题的行。您的第二个
strtok()
调用应将NULL
作为其第一个参数。请参阅文档。结果工作代码是:
输出
There are 2 problems:
Make
str
of typechar[]
. GCC gives the warningfoo.cpp:5: warning: deprecated conversion from string constant to ‘char*’
which indicates this is a problematic line.Your second
strtok()
call should haveNULL
as its first argument. See the docs.The resulting working code is:
which outputs
我不确定什么是“总线”错误,但如果您想继续解析相同的字符串,循环中 strtok() 的第一个参数应该为 NULL。
否则,您将继续从同一字符串的开头开始,顺便说一句,在第一次调用 strtok() 之后,该字符串已被修改。
I'm not sure what a "bus" error is, but the first argument to strtok() within the loop should be NULL if you want to continue parsing the same string.
Otherwise, you keep starting from the beginning of the same string, which has been modified, by the way, after the first call to strtok().