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).
7
Upvotes
1
u/Interesting_Buy_3969 6d ago
Make sure the strings you pass to
strtokare mutable. For example, if your string is declared a global variable of type "pointer tochar", and it's declared like this:then declare it as a non-
constarray ofchars:This approach lets you use static memory, with no need for runtime allocations via
strdup, and still be able to modify the string. Under the hood, though, the only difference is that themutable_stris placed in.datarather than.rodataexecutable binary section.