Why is strtok causing a segmentation fault?

c, segmentation-fault, string

Solution

strtok modifies its first argument, hence it should be modifiable.

Maybe ReadName() returns a pointer to a read-only char array.Can you show us your ReadName() function.

If that is the reason for seg-faullt, you can create a copy of the char array before you pass it to strtok using the strdup function like:

char *copy = strdup(m);
token = strtok(copy,'-');
....
....
free(copy); // free the copy once you are done using it.

Problem

Why does the below code give Seg. Fault at last line? ``` char* m=ReadName(); printf("\nRead String %s\n",m); // Writes OK char* token; token=strtok(m,'-'); ``` As said, read string prints w/o problem, but why cannot split to tokens?

Original source

Related problems