Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error in strtok function in C

Tags:

c

string

strtok

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

like image 881
user496934 Avatar asked Dec 17 '22 13:12

user496934


1 Answers

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.

like image 157
Oliver Charlesworth Avatar answered Dec 30 '22 18:12

Oliver Charlesworth