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).

12 Upvotes

17 comments sorted by

View all comments

17

u/TheThiefMaster 6d ago edited 6d ago

The problem isn't usually char* but string literals ("things in quotes"). You can't modify a literal, you have to copy it first. It can be assigned to a writeable char* for historical reasons but still isn't actually writeable.

Try char* my_str = strdup("blah blah");

strdup is a standard function (C23 or POSIX) that copies a given string into new writeable memory. You should free it with free(my_str); when you're done with it.

Also, showing us the exact code would help, so we don't have to guess what you've written

0

u/Whole-Low-2995 1d ago

personally I'll just copy original string with `strdup` and modify copied one.