I have following snippet where value of pointer is printed, since it is pointer, on 64 bit machine, its size is 8 bytes, and 64 bits should be used to represent the address, But:
#include <stdio.h>
int main()
{
char *s = "";
printf("%p %p\n", s, (char*)(int)s);
return 0;
}
But output is :
0x4005e4 0x4005e4
why only 24 bits are used for the pointer value, shouldn't this be 64 bits ?
Also, is it UB if cast of different size pointer are involved like here (char *)(int)s ?
What I was expecting with this (char)s to give only 1 Byte address but it is printing 8 bytes address?
CodePudding user response:
why only 24 bits are used for the pointer value
Your pointers happen to have their most significant bits set to zero, so they aren't printed. If you really want to print all 64 bits, you can change your printf format string to make it print leading zeros.
is it UB if cast of different size pointer are involved like here (char *)(int)s ?
There are no "different size pointers" on the machines you're likely to be using, but int
is commonly 32 bits. So by casting through int
on the way to char*
, you are throwing away the most significant 32 bits. If they were zero, you may not notice the difference, but if not you'll corrupt the pointer and nobody knows what you'll get if you dereference it. You can still print its value (i.e. the address it points to, even if it's nonsense).