Possible Duplicate:
Why do I get a segmentation fault when writing to a string?
I’m experiencing a strange issue with my C code. I’m trying to split string using strtok function, but I get access violation exception. Here’s my code:
char *token;
char *line = "LINE TO BE SEPARATED";
char *search = " ";
token = strtok(line, search); <-- this code causes crash
However, if I change char *line to char line[], everything works as expected and I don’t get any error.
Anyone can explain why I get that (strange for me) behavior with strtok? I thought char* and char[] was the same and exact type.
UPDATE
I’m using MSVC 2012 compiler.
When assigning
"LINE TO BE SEPARATED"tochar *line, you makelinepoint to an constant string written in the program executable. You are not allowed to modify it. You should declare those kind of variable asconst char *.When declared as
char[], your string is declared on the stack of your function. Thus, you are able to modify it.