apparent discrepancy with sizeof and addressof

183 Views Asked by At

sizeof(long) returns 8 bytes but the &along (address of a long) is 12 hex digits (48-bits) or 6 bytes. On OS X 64-bit compiled with clang. Is there a discrepancy here or is this a genuine 64-bit address space?

4

There are 4 best solutions below

0
On BEST ANSWER

In effect modern systems use 64 bit for addresses but not all of these are used by the system since 2 to the 64 is an amount of memory no one will use in a near future. Under linux you can find out what your machine actually uses by doing cat /proc/cpuinfo. On my machine I have e.g

address sizes : 36 bits physical, 48 bits virtual

so this would allow for 64 GiB of physical memory and 256 TiB of virtual memory. This is largely enough for what this machine will ever encounter.

1
On

I think you're conflating two different concepts. Sizeof tells you how long a long is, not now long an address is. A long takes up six bytes of memory, but the pointer to it (apparently) takes only 6 (or more likely, takes 8, but the first two are all-zero because of how the memory is laid out)

Let me expand some explanation about address spaces. While pointers are 8 bytes long in a 64 bit processor, the address space rarely needs that much. That allows 2^64 bytes to be addressed, much more than we need. So, for simplicity, many processors and compilers only use 48 of those bits. See this wikipedia link for a few useful diagrams:

http://en.wikipedia.org/wiki/X86-64#Canonical_form_addresses

1
On

I'm not sure if this is the exact reason why you're seeing this, but current 64-bit processors typically don't actually have a 64-bit address space. The extra hardware involved would be a waste, since 48 bits of address space is more than I expect to need in my lifetime. It could be that you're seeing a truncated version of the address (i.e., the address is not being front-padded with zeros).

3
On

An address us a memory location. On a 32-bit system it will be 32-bits long, on a 64-bit system 64-bits, and so on.

The sizeof of variable is how much memory it occupies. They are completely unrelated numbers.

sizeof(long) returns 8 bytes but the &along (address of a long) is 12 hex digits (48-bits) or 6 bytes.

Yes, because when you print a number the leading 0's aren't printed. For example:

int x = 0x0000000F;
printf( "%X", x );
// prints "F"