r/learnprogramming • • Oct 07 '26

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

Show parent comment

2

u/mredding Oct 07 '26

C has no concept of copy elision.

What the compiler generates is compiler specific to the platform. The C spec does not make any comment on these details, as C is a high level language that targets an abstract machine, it is not a high level assembly - despite as often as it is treated like one.

But what GCC will do for the x86 platform depends on factors such as where in the program the array is scoped, and how large it is.

Since the literal is entirely known at compile-time, initialization may consist of a series of mov operations where the string text is packed into registers, some 4 bytes at a time or more. This may mean the literal may not actually get compiled into RO memory.

Another option is to call put that string into RO memory, and memcpy, which is just a series of shifting bytes into memory and calling mov in a loop.

Another option is for the compiler to generate machine instructions similar to what memcpy would determine and select, but at compile-time. memcpy will choose a strategy based on a number of properties, but it comes down to either a simple mov instruction for CPU cache friendly values, some AVX instructions for bulk copying, or specialized ERMS instructions for copying memory addresses while bypassing CPU registers and cache.

Whatever the compiler chooses, it'll be based on heuristics and a best effort to maximize whatever you prioritize - size or speed.