2

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!

Legolas
  • 49
  • 6
  • [See also](http://stackoverflow.com/questions/4480552/why-does-the-following-c-program-give-a-bus-error) – Casey Kuball Dec 07 '16 at 15:24
  • Also, Your code above is missing a `)` before the `;` on the `for()` line. (and quite possibly some `{`, `}`) – Toby Dec 07 '16 at 16:25

2 Answers2

5

You cannot modify a string constant. Define line this way:

char line[] = "test test test";
chqrlie
  • 131,814
  • 10
  • 121
  • 189
3

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";

Govind Parmar
  • 20,656
  • 7
  • 53
  • 85