I am using a simple program to tokenize a string using strtok function. Here is the code -
# include <stdio.h>
char str[] = "now # time for all # good men to # aid of their country"; //line a
char delims[] = "#";
char *result = NULL;
result = strtok( str, delims );
while( result != NULL ) {
printf( "result is \"%s\"\n", result );
result = strtok( NULL, delims );
}
The program runs successfully. However, if line a is changed to
char * str= "now # time for all # good men to # aid of their country"; //line a
The strtok function gives a core dump. I would like to get an explanation for my understanding why this is so ? Because from the declaration of strtok as --char *strtok( char *str1, const char *str2 ); char *str as the first argument should work
char *str = "foo"
gives you a pointer to a string literal (you should really be doing const char *
, but C allows non-const
for backwards compatiblity reasons).
It is undefined behaviour to attempt to modify a string literal. strtok
modifies its input.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With