Segmentation fault (core dumped) in strtok [duplicate]
Possible Duplicate:
Memory Allocation char* and char[]
Why does the开发者_运维百科 following program give a Segmentation fault in run-time ?
#include <stdio.h>
#include <string.h>
#include <malloc.h>
main()
{
char * str = "Have a. nice, day :)";
char * ptr;
ptr = strtok( str, " .,");
printf("%s",ptr);
}
But if I use char str[] = "Have a. nice, day :)"; it gives me the output. Why is that i get the error even though strtok definition is char* strcpy( char * , const char * ) ???~
strtok
modifies the argument, str
points to a string literal, modifying a string literal causes undefined behavior. Initializing a non-const char*
with a string literal is in fact deprecated.
When you write str[]
, str
becomes a mutable array initialized with the string.
strtok modifies the string passed to it. I suspect it has something to do with char * = "literal string" giving you a pointer to the string in the .data section, while char[] = "literal string" allocates a buffer on the stack, and copies the initial contents from the .data section.
精彩评论