3

When I do

int k = 9;
printf("sizeof k: %zu \n", sizeof (&k));

I get the size as 8. But when I do

printf("pointer to k: %p \n", &k);

I get 0x7fff57e3ba24. I can see that this is 12 hex numbers which means (since 1 hex is 4 bits) that the pointer occupies 48 bits which is 6 bytes.

The question: Why does sizeof print 8 for pointer although its only 6 bytes?

user10607
  • 3,011
  • 4
  • 24
  • 31
  • 2
    http://www.viva64.com/en/a/0050/ – Ivan Ivanov Oct 10 '14 at 06:14
  • While the amd64 ISA uses 64-bit pointers, in fact only 48 bits are currently used. So on most desktop systems today, you will indeed see "48 bit" pointers stored in 64 bit slots. – John Zwinck Oct 10 '14 at 06:17
  • @JohnZwinck Because no address exists at such a "far away" location to occupy the whole 64 bits? (The memory does not have so many slots in other words?) – user10607 Oct 10 '14 at 06:26
  • @user10607: see here: http://stackoverflow.com/questions/6716946/why-do-64-bit-systems-have-only-a-48-bit-address-space – John Zwinck Oct 10 '14 at 06:27
  • Wow by reading this post I got really really confused .. Can anyone tell me doesnt integer `int` supposed to allocate only 4 byte of memory wheather it be a pointer or a regular variable ? Please anyone reply or paste a link so that my confusion would be helped . Thanks!! – Asis Oct 10 '14 at 07:17
  • @Asis after some reading: 8 bytes for a pointer to int (or other basic type), 4 bytes for int. Note that in the question I use '&k' which is a pointer to int. – user10607 Oct 10 '14 at 07:32

3 Answers3

8

Your logic is that if I write

printf("%d", 4); 

and it prints 1 decimal digit, which can potentially be stored in 1 byte, then sizeof(int) must be 1 byte.

The number 0x7fff57e3ba24 is the same as 0x00007fff57e3ba24. Just because the number happens to have fewer digits than the type can store doesn't mean it occupies any less space.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434
3

You pointer still occupies 8 bytes even if most significant bits are zeroes.

Although it is possible to "optimize" data storage by eliminating unneeded bytes data access would become much more complicated and less efficient. Have a read about data alignment in computer memory.

dmitri
  • 3,183
  • 23
  • 28
1

Leading zeros have no significance , since addresses are unsigned leading 2 bytes are zeroes hence not printed. You could modify format specifier to print leading zeros.

Satyajit R
  • 72
  • 4