Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between array and pointer to string literal

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.

like image 338
user2392631 Avatar asked Sep 15 '25 06:09

user2392631


2 Answers

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.

like image 94
Shafik Yaghmour Avatar answered Sep 16 '25 21:09

Shafik Yaghmour


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.

like image 21
selva Avatar answered Sep 16 '25 19:09

selva