Difference between array and pointer to string literal
c, memory-management, undefined-behavior
Solution
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`.
Problem
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.