char *strtok(char *s1, const char *s2)
repeated calls to this function break string s1 into ‘tokens’–that is the string is broken into substrings, each terminating with a ‘\0’, where the ‘\0’ replaces any characters contained in string s2. The first call uses the string to be tokenized as s1; subsequent calls use NULL as the first argument. A pointer to the beginning of the current token is returned; NULL is returned if there are no more tokens.
Hi,
I have been trying to use strtok just now and found out that if I pass in a char* into s1, I get a segmentation fault. If I pass in a char[], strtok works fine.
Why is this?
I googled around and the reason seems to be something about how char* is read only and char[] is writeable. A more thorough explanation would be much appreciated.
What did you initialize the
char *to?If something like
then you have a pointer to some read-only characters
For
then you have a seven element array of characters that you can do what you like with.
strtokwrites into the string you give it – overwriting the separator character withnulland 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
strtokkeeps 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)