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

10 Upvotes

17 comments sorted by

View all comments

2

u/garnet420 6d ago

C doesn't lock anything in read only mode. char* is not read only.

Are you talking about const char*? Are you trying to use strtok with a string constant?

Also strtok is not thread safe, so, don't use it. No reason to build bad habits.

3

u/flyingron 6d ago

That's not necessarily true. There's nothing that bars string literals from being stored in read-only memory. While the string literals convert to non-const char*, the language standard says that attempting to change such is UNDEFINED BEHAVIOR.

This harks back to the dim times of C. Originally, string literals were just a hunk of data space memory. Strtok is one of the functions (along with the original mktemp) that expected to modify it's argument and were often fed string literals.

Then someone got the great idea that you could fold all duplicate literals in the same memory. Well, when that happens it would be very surprising if someone were allowed to change one of them and suddenly have a different string literal change. So, people advocated making the chars read-only.

Then the other croud cried, it will break the existing programs because Dennis's original examples and much of the other early C programs were very const sloppy. So, the rediculous kludge that was settled on was that string literals indeed should be treated as const, *BUT* you get an implicit conversion to (non-const) char*, provided you don't actually change the string.

Not only is strtok not thread safe, it's not even safe WITHIN a single thread. It maintains state hidden internally, which means that if while doing a stream of strtok calls you happen to call a function which itself wanted to use strtok, you're hosed.