Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is strtok causing a segmentation fault?

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?

like image 735
paul simmons Avatar asked Nov 30 '22 11:11

paul simmons


1 Answers

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.
like image 193
codaddict Avatar answered Dec 15 '22 05:12

codaddict