dud3 dud3 - 2 months ago 18
C Question

Printing two string literals with same value gives same address

Can someone explain the following:

#include <stdio.h>

void some_fn(char *x)
{
printf("%d\n", x);
}

int main()
{
// They are stored on the same memory address
some_fn("A");
some_fn("A");

some_fn("B");
}


Why would:

some_fn("A");
some_fn("A");


print be stored on the same memory address?

Answer

First, off using %d to print a pointer (as you had in your code originally before you edited it) is invalid and results in undefined behavior. You should use the %p pointer instead.

That being said, the two calls to some_fn are both being passed a string literal, each of which happens to be the same. String literals are typically stored in a read-only section of memory, and when a particular string literal appears in the code multiple times, the compiler will typically use a single instance of that literal. So in that case the address of that literal is the same when it appears in different places.