-2

Consider the following code:

int main() {
    char *p = "abcd";
    p[0] = 'x';
    return 0;
}

Is it guaranteed by the standard to work in any environment?

I am worried that some compilers my decide to mark the memory where the string is stored as read only and attempting to modify it would generate a segmentation fault at runtime. However, on all environments I tested it, it worked.

Paul92
  • 8,827
  • 1
  • 23
  • 37

2 Answers2

6

Standard confirms that any modification to string literal may lead to undefined behavior.

C11- §6.7.9/32

[...] The contents of the arrays are modifiable. On the other hand, the declaration

  char *p = "abc";

defines p with type "pointer to char" and initializes it to point to an object with type "array of char" with length 4 whose elements are initialized with a character string literal. If an attempt is made to use p to modify the contents of the array, the behavior is undefined.

Note that when undefined behavior is invoked then you may get either expected or unexpected results. In this case it is not guaranteed that you will always get segmentation fault or program crash.

Suggested reading: comp.lang.c FAQ list · Question 8.5

haccks
  • 104,019
  • 25
  • 176
  • 264
2

It's not, it's actually undefined behaviorone of the items in the list says A program attempts to modify a string literal . Why would you think that it works? Oh yeah right, a simple test. Undefined behavior is not defined so maybe the program will crash, and maybe it wont. IT'S UNDEFINED.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
  • I have edited my question. I haven't managed to make it crash on multiple environments, even if my intuition says is shouldn't work. – Paul92 Jan 03 '16 at 20:25
  • 1
    @Paul92; It is not guaranteed to crash always. Read about undefined behavior(link is given in this answer). – haccks Jan 03 '16 at 20:44
  • 1
    To complement @haccks comment, if it were guaranteed to do something like crashing it would not be undefined behavior. – Iharob Al Asimi Jan 03 '16 at 20:45