Home > OS >  Void pointer to a string printing incorrect address
Void pointer to a string printing incorrect address

Time:08-24

I am using a void pointer which is assigned to a string. But it is returning me an incorrect address. The way I verified the address of my void pointer was through checking in the elf file. elf file denotes a different address & printf is showing different address.

void *str;
str = "TestString";
printf("%p",str);

Moreover if I use this code twice , it prints the same address. Which makes me believe that it definitely isn't address.

void *str;
str = "TestString";
printf("%p\n",str);
void *str2;
str2 = "TestString";
printf("%p",str2);

Can someone please tell me what exactly is it printing & how can I get the address ?

CodePudding user response:

Compilers commonly implement something called "string pooling", meaning that identical string literals are stored at the same address, in order to save memory. Which makes perfect sense since they are read-only anyway. It is easy enough to verify that this is the case by checking the disassembly generated by any compiler.

For example gcc x86 only allocates a single string literal in your example. Even with optimizations disabled, there's only a single .string "TestString" present in the disassembly.

If you for some reason need unique addresses, use variables instead:

const char str[] = "TestString";
printf("%p\n", (void *)str);
const char str2[] = "TestString";
printf("%p", (void *)str2);
  • Related