Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Addresses of two char pointers to different string literals are same

#include<stdio.h> #include<string.h>  int main() {     char * p = "abc";     char * p1 = "abc";     printf("%d %d", p, p1); } 

When I print the values of the two pointers, it is printing the same address. Why?

like image 565
seereddi sekhar Avatar asked Sep 30 '13 06:09

seereddi sekhar


People also ask

Where are string literals stored in C?

String literals are stored in C as an array of chars, terminted by a null byte. A null byte is a char having a value of exactly zero, noted as '\0'.

What is string literal?

A "string literal" is a sequence of characters from the source character set enclosed in double quotation marks (" "). String literals are used to represent a sequence of characters which, taken together, form a null-terminated string.

Can you change a string literal?

The behavior is undefined if a program attempts to modify any portion of a string literal. Modifying a string literal frequently results in an access violation because string literals are typically stored in read-only memory.


2 Answers

Your compiler seems to be quite clever, detecting that both the literals are the same. And as literals are constant the compiler decided to not store them twice.

It seems worth mentioning that this does not necessarily needs to be the case. Please see Blue Moon's answer on this.


Btw: The printf() statement should look like this

printf("%p %p", (void *) p, (void *) p1); 

as "%p" shall be used to print pointer values, and it is defined for pointer of type void * only.*1


Also I'd say the code misses a return statement, but the C standard seems to be in the process of being changed. Others might kindly clarify this.


*1: Casting to void * here is not necessary for char * pointers, but for pointers to all other types.

like image 37
alk Avatar answered Sep 17 '22 17:09

alk


Whether two different string literals with same content is placed in the same memory location or different memory locations is implementation-dependent.

You should always treat p and p1 as two different pointers (even though they have the same content) as they may or may not point to the same address. You shouldn't rely on compiler optimizations.

C11 Standard, 6.4.5, String literals, semantics

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.


The format for printing must be %p:

  printf("%p %p", (void*)p, (void*)p1); 

See this answer for why.

like image 197
P.P Avatar answered Sep 19 '22 17:09

P.P