1

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?

Community
  • 1
  • 1
Thomas
  • 17,016
  • 4
  • 46
  • 70
  • 1
    Look at the search results. LOOK AT THEM!@#! http://stackoverflow.com/search?q=strcpy+segmentation+fault – flight Sep 22 '11 at 01:23
  • What is the best duplicate? I couldn't readily find it. – erisco Sep 22 '11 at 01:27
  • 2
    They're NOT all exact duplicates, but the mistake(s) are generally the same. – Mysticial Sep 22 '11 at 01:28
  • I agree John Kugelman. Moving to close for duplication. – erisco Sep 22 '11 at 01:29
  • @quasiverse: Before asking this question I saw that there are a lot of similar questions here on SO, but almost all of them are the other way around, namely declaring `char *text;` without allocating memory. – Thomas Sep 22 '11 at 04:08

3 Answers3

6

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*.

Marlon
  • 19,924
  • 12
  • 70
  • 101
0

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

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
0

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.

iammilind
  • 68,093
  • 33
  • 169
  • 336