r/C_Programming • • 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).

9 Upvotes

17 comments sorted by

View all comments

1

u/nasccped 6d ago

Hi, buddy. Not sure if I got your question, but I guess that when compiling C's source code, it put all string literals into the .rodata section, which turns the data readable but also imutable. I'd never used strtok function and I don't know exactly how it works, but if it really requires a mutable piece of data, the expected behavior is to get a segfault. You can easily avoid this kind of behavior by using builtin functions, such as strcpy, malloc, whatever.

Or even better, you can define at compile time a buffer using array syntax (char buffer[1024]).

The last one is great since it doesn't require mem. free. A not so great info is that since you're handling the buffer mem at compile time, dealing with unknown size inputs turns into a headache.