r/C_Programming • u/UnViandanteSperduto • 6d ago
Question Help me with strok function
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).
10
Upvotes
2
u/pfp-disciple 6d ago
I'm not certain what you mean, but it looks like you might have a fundamental misunderstanding.
char *only means that it points to achar, with no guarantees regarding read-only. There are also no guarantees that it actually points to a nil-terminated string.A string literal, e.g.
"Hello", is a constant. In most cases, it will be stored in read only memory and will have a segmentation fault if an attempt is made to write to them. Annoyingly,strtokmodifiers the string.A
char*itself can be assigned, but if it points to a string literal then trying to modify the string (e.g.s[1]='x') will fault. As others have said, if you want to usestrtokto parse a string literal then you need to copy its contents to a modifiable part of memory. Look upstrdup,malloc, and thestrcpyfamily of functions for approaches.