Possible Duplicate:
Getting Segmentation Fault
Why does this code cause a segmentation fault?
char *text = "foo";
strcpy(text, "");
As far as I understand it, the first line allocates some memory (to hold the string “foo”) and text points to that allocated memory. The second line copies an empty string into the location that text points to.
This code might not make a lot of sense, but why does it fail?
Whenever you have a string literal (in your case, “foo”), the program stores that value in a readonly section of memory.
strcpywants to modify that value but it is readonly, hence the segmentation fault.Also,
textshould be aconst char*, not achar*.