Question

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?

Was it helpful?

Solution

Whenever you have a string literal (in your case, "foo"), the program stores that value in a readonly section of memory.

strcpy wants to modify that value but it is readonly, hence the segmentation fault.

Also, text should be a const char*, not a char*.

OTHER TIPS

Because a string literal (like "foo") is read-only.

Because the string literals are stored in the read only region of memory.

Thus attempting the modification of foo(using strcpy in this case) is an undefined behavior.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top