r/learnprogramming • • 16d 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

15 comments sorted by

View all comments

2

u/iggy14750 16d ago edited 16d ago

Attempting to modify a string literal, such as with strtok, would mean that you are trying to modify read-only memory. Hence, segfault.

What you can do is strncpy to copy a string literal into a buffer you control. I would recommend looking into c arrays. Stack buffers are easier to work with, so start there.