Addresses of two char pointers to different string literals are same Addresses of two char pointers to different string literals are same c c

Addresses of two char pointers to different string literals are same


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.


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.


Your compiler has done something called "string pooling". You specified that you wanted two pointers, both pointing to the same string literal - so it only made one copy of the literal.

Technically: It should have complained at you for not making the pointers "const"

const char* p = "abc";

This is probably because you are using Visual Studio or you are using GCC without -Wall.

If you expressly want them to be stored twice in memory, try:

char s1[] = "abc";char s2[] = "abc";

Here you explicitly state that you want two c-string character arrays rather than two pointers to characters.

Caveat: String pooling is a compiler/optimizer feature and not a facet of the language. As such different compilers under different environments will produce different behavior depending on things like optimization level, compiler flags and whether the strings are in different compilation units.