3

Possible Duplicate:
strtok giving Segmentation Fault

Why do i get segfault using this code ?

void test(char *data)
{
    char *pch;
    pch = strtok(data, " ,.-"); // segfault
    while (pch != NULL)
    {
        printf("%s\n", pch);
        pch = strtok(NULL, " ,.-");
    }

    return NULL;
}

char *data = "- This, a sample string.";
test(data);
Community
  • 1
  • 1
artyomboyko
  • 2,781
  • 5
  • 40
  • 54
  • 2
    This has been asked [many](http://stackoverflow.com/questions/2385697/strtok-giving-segmentation-fault) [times](http://stackoverflow.com/questions/5925405/problem-with-strtok-and-segmentation-fault) [before](http://stackoverflow.com/questions/272876/cs-strtok-and-read-only-string-literals). – Adam Rosenfield Aug 17 '11 at 22:29

2 Answers2

16

strtok() modifies the original string. You are passing it a constant source string that cannot be modified.

Try this instead:

char *data = strdup("- This, a sample string.");
test(data);
Evan Mulawski
  • 54,662
  • 15
  • 117
  • 144
hookenz
  • 36,432
  • 45
  • 177
  • 286
  • 7
    Or simply `char data[] = "- This, a sample string.";` – caf Aug 17 '11 at 22:22
  • The modified code will demonstrate a version that won't crash because the compile time string literal is copied to a new heap allocated buffer allowing strtok to work. – hookenz Aug 17 '11 at 22:22
  • 2
    That's going to create a memory leak though, unless you remember to free data after you are done. – Mikola Aug 17 '11 at 22:24
  • ...and the alternative I suggest won't crash either, because the compile-time string literal is copied to a new stack allocated buffer. – caf Aug 17 '11 at 22:26
  • 3
    Also note that `strdup` is not part of ANSI C, but POSIX. – Evan Mulawski Aug 17 '11 at 22:29
4

strtok modifies the string. You are passing a pointer to read-only data (a string constant).

Try using a char array.

char data[] ="- This, is a sample string."
test(data);
Tom
  • 43,810
  • 29
  • 138
  • 169