Why is strtok causing a segmentation fault?
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.
token=strtok(m,'-');
should generate a compiler warning because the second parameter of strtok()
is a const char *
pointing to multiple delimiters, not a single char
delimiter:
char *strtok(char *str, const char *delim);
The ASCII code of '-'
is 0x2D, so passing it as the second parameter of strtok()
will cause strtok()
to dereference the address 0x0000002D, which will cause a segfault or access violation on most modern operating systems. To fix this, use a string literal instead of a character literal: token=strtok(m,"-");
There's also the issue of how the return value of ReadName()
is allocated, which others have addressed in their answers.