Why does writing to a string literal in this C program segfault?

It is undefined behavior to try to overwrite a string literal. C99 §6.4.5/6:

If the program attempts to modify such
an array, the behavior is undefined.

This is restated in Appendix J.2 (undefined behavior).

If you instead do:

char p[] = "nyks";

you can allocate and initialize an automatic (stack) character array. In that case, it is perfectly fine to modify elements.

Leave a Comment