I am new to C, so it may be a dumb question. I was writing a piece of code like bellow:
char ar[]="test";
*(ar+1)='r';
this is working fine. But whenever I am doing it:
char *p="test";
*(p+1)="r";
this is giving segmentation fault. Can anyone please describe why second case is giving segmentation fault? explanation from memory point of view will be appreciated.
In the second case p
is pointing to a string literal and you are not allowed to modify a string literal, it is undefined behavior. From the C99 draft standard section 6.4.5
String literals paragraph 6 (emphasis mine):
It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.
In the first case ar
is an automatic variable and you are allowed to modify it since it not const qualified. The contents of the string literal are being copied during initialization or ar
.
In a c , whenever u store a string in an array, you could allow to change the content of the string . the reason for this, c store the content of string in a consecutive memory.
In the case of pointer , the pointer stored the starting address of the string and it assumes that would be constant . suppose , you try to change it. you get an undefined behavior , even the worse case is , you cant find it easily just because it wont be throw any error regarding this.
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