1

Possible Duplicate:
Why do I get a segmentation fault when writing to a string?

I want to replace a word in a string. Here is the code

char text[] = "This is a list of lists";
char *find = "list";
char* pos = NULL;
pos = strstr(text,find);
strncpy(pos,"test",4)

This works fine but

char *text = "This is a list of lists";
char *find = "list";
char* pos = NULL;
pos = strstr(text,find);
strncpy(pos,"test",4)

This gives a segmentation fault.

In the first example "text" is an array and the data is just copied at that location. In the 2nd one "text" is a pointer. What is issue?

Community
  • 1
  • 1
MPJ
  • 19
  • 1
  • 2
  • 4
    AHHH! You're modifying a string literal. Head for cover! Hang on while I find a dupe. – Mysticial Sep 14 '12 at 05:43
  • The string literal is still located in my memory.Should i not be able to change it? – MPJ Sep 14 '12 at 05:48
  • Read the dupe that I linked. It has a very clear explanation. Basically, not all memory is modifiable. – Mysticial Sep 14 '12 at 05:49
  • Ah yes, the daily "why do my program crash when I modify a string literal"-question. It came earlier today than yesterday. – Lundin Sep 14 '12 at 06:39

2 Answers2

3

The difference between

char text[] = "This is a list of lists"; // 1

and

char *text = "This is a list of lists"; // 2

is that, in (1), text is a non-constant array of characters; where as in (2), text points to a string literal, and string literals are are constant. You can't modify constant objects, which you're trying in (2). What you're doing in (2) in actually undefined behaviour.

Donotalo
  • 12,748
  • 25
  • 83
  • 121
  • Does C allow for changing the literals somehow? – MPJ Sep 14 '12 at 05:55
  • @MPJ: i don't think C standard allows it. literals are supposed to be constant and you're not supposed to modify it. but your compiler may have some flag that may allow it. i don't see any reason you need to modify constant object though. you can `strcpy` any string literal to a character array and then modify the array as you wish. – Donotalo Sep 14 '12 at 06:17
1

The problem is the string in the second example is a string literal, which must remain constant. When you try to write on that string you are writing to read-only memory, which (depending on the operating system) is not allowed.

epsalon
  • 2,294
  • 12
  • 19