Reputation: 49
Here is my code, when I running the code, always bus error 10:
void print_tokens(char *line)
{
static char whitespace[] = " \t\f\r\v\n";
char *token;
for(token = strtok(line, whitespace);
token != NULL;
token = strtok(NULL, whitespace))
printf("Next token is %s\n", token);
}
int main(void)
{
char *line = "test test test";
print_tokens(line);
return 0;
}
Please help me!
Upvotes: 2
Views: 1966
Reputation: 21562
strtok
will modify the buffer it is passed; this is contractual:
Be cautious when using these functions. If you do use them, note that:
* These functions modify their first argument.
* These functions cannot be used on constant strings.
When you declare a string as char *str = "blah blah";
in C, you are declaring it to be read-only memory, so when you pass it to strtok
the result is undefined since strtok
wants to modify the buffer but can't since it's read-only.
To address this issue declare str
as an array instead: char str[] = "blah blah";
Upvotes: 3
Reputation: 144951
You cannot modify a string constant. Define line
this way:
char line[] = "test test test";
Upvotes: 6