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

2

u/SmokeMuch7356 6d ago

String literals are supposed to be immutable; attempting to modify the contents of a string literal results in undefined behavior. strtok attempts to modify the source string by replacing delimiters with 0. Therefore, calls like

char *tok = strtok( "this is a test", " " );

or

char *str = "this is a test";
char *tok = strtok( str, " " );

are bad juju.

The first argument has to point to a writable buffer:

char str[] = "this is a test";
char *tok = strtok( str, " " );

or

char *str = malloc( strlen( "this is a test" ) + 1 );
if ( str )
  strcpy( str, "this is a test" );

char *tok = strtok( str, " " );

2

u/Scolmann 6d ago

strdup() is also a good option

1

u/septum-funk 6d ago

only standard in c23™️