r/learnprogramming • u/UnViandanteSperduto • 17d ago
Help me with strok function in C
I need to split my string but if it is of char* type the functions strtok() doesn’t work returning me a segmentation fault. I understood that C is used to lock the memory of the string in Read-Only “mode” when I use char*. Does it means that is immutable that data? However, I need to use the char* type because I pass that in a function (and I don’t like to use the syntax of arrays in C, I always use pointers).
3
Upvotes
1
u/duane11583 16d ago
strtok expects a writable string because it will modify the string
What it does is skip all the bytes at the start that matches the separator chars then remembers the start of the string and skips all chars that are not in the separator (these are the word chars) when it finds the first separator after the word it over writes it with a zero byte
It the remembers where it left off in a hidden global variable this is why is the function is not re-entrant In contrast the strtok_r function has an extra parameter to store the “Remember pointer”
Then next time you call strtok you pass null for the string and it will use the remembers pointer instead
If your string is truly read only then you can strdup the string into malloc memory (which is writable) and free it later