#include<stdio.h>
void main()
{
char *p="nyks";
p[2]='n';
printf("%s",p);
}
This crashes with a SEGMENTATION FAULT. Can someone explain why?
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.
The standard dictates that literal strings are defined const. You cannot change it.
The compiler places the literal in a readonly memory section. You can output the assembly and observe this. If you are using GCC it is done via the -s flag. It will place the string in a .rodata section.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With