What did you initialize the char *
to?
If something like
char *text = "foobar";
then you have a pointer to some read-only characters
For
char text[7] = "foobar";
then you have a seven element array of characters that you can do what you like with.
strtok
writes into the string you give it – overwriting the separator character with null
and keeping a pointer to the rest of the string.
Hence, if you pass it a read-only string, it will attempt to write to it, and you get a segfault.
Also, becasue strtok
keeps a reference to the rest of the string, it’s not reeentrant – you can use it only on one string at a time. It’s best avoided, really – consider strsep(3) instead – see, for example, here: http://www.rt.com/man/strsep.3.html (although that still writes into the string so has the same read-only/segfault issue)