[英]Why does the following C program give a bus error?
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.
我写了C已经有一段时间了,我不知所措。 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;
}
String literals should be assigned to a const char*, as modifying them is undefined behaviour. 字符串文字应该分配给const char *,因为修改它们是未定义的行为。 I'm pretty sure that strtok modifies it's argument, which would explain the bad things that you see.
我很确定strtok修改了它的参数,这可以解释你看到的坏事。
There are 2 problems: 有两个问题:
Make str
of type char[]
. 创建类型为
char[]
str
。 GCC gives the warning foo.cpp:5: warning: deprecated conversion from string constant to 'char*'
which indicates this is a problematic line. GCC给出了警告
foo.cpp:5: warning: deprecated conversion from string constant to 'char*'
表明这是一个有问题的行。
Your second strtok()
call should have NULL
as its first argument. 你的第二个
strtok()
调用应该有NULL
作为它的第一个参数。 See the docs . 查看文档 。
The resulting working code is: 生成的工作代码是:
#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;
}
which outputs 哪个输出
one
two
three
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. 我不确定是什么“总线”错误,但如果你想继续解析相同的字符串,循环中strtok()的第一个参数应为NULL。
Otherwise, you keep starting from the beginning of the same string, which has been modified, by the way, after the first call to strtok(). 否则,在第一次调用strtok()之后,顺便从第一个字符串的开头开始。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.