8

I am using c++ under 64 bit linux, the compiler (g++) is also 64 bit. When I print the address of some variable, for example an integer, it is supposed to print a 64 bit integer, but in fact it prints a 48 bit integer.

int i;
cout << &i << endl;

output: 0x7fff44a09a7c

I am wondering where are the other two bytes. Looking forward to you help.

Thanks.

cheng
  • 2,106
  • 6
  • 28
  • 36
  • How many bits does the number `1` have? Would you complain that `uint32_t x = 1;` doesn't have enough bits? You should check `sizeof(*int)` rather than print things. – Kerrek SB Aug 25 '11 at 12:58

3 Answers3

8

The printing of addresses in most C++ implementations suppresses leading zeroes to make things more readable. Stuff like 0x00000000000013fd does not really add value.

When you wonder why you will normally not see anything more than 48bit values in userspace, this is because the current AMD64 architecture is just defined to have 48bit of virtual address space (as can be seen by e.g. cat /proc/cpuinfo on linux)

PlasmaHH
  • 15,673
  • 5
  • 44
  • 57
  • This Wikipedia (yeah, I know) article says the architecture definition allows up to 64 bits, but current implementations only use 48. Is it wrong? http://en.wikipedia.org/wiki/Amd64#Architectural_features – AndrzejJ Aug 25 '11 at 13:16
  • @AndrzejJ Well it's a "64bit" architecture and nominally the pointers are 64bit. It's just that currently 256TB virtual address space is more than enough and you save wires (and therefore power) if you can just assume that the higher 16bits of every pointer are zero.. – Voo Aug 25 '11 at 13:26
3

They are there - they haven't gone anywhere - it's just the formatting in the stream. It skips leading zeros (check out fill and width properties of stream).

EDIT: on second thoughts, I don't think there is a nice way of changing the formatting for the default operator<< for pointers. The fill and width attributes can be changed if you are streaming out using the std::hex manipulator.

Nim
  • 33,299
  • 2
  • 62
  • 101
  • So if the address of some object is 0x400c10, that means 5 bytes of leading zeros are omitted, right? – cheng Aug 25 '11 at 13:00
  • 1
    @user508305 It might, but note that all pointers aren't necessarily the same size as the platform addressing capability. – Šimon Tóth Aug 25 '11 at 13:02
  • In what case do they have different size? Can you talk more about this or just give me some keywords so that I can google it. – cheng Aug 25 '11 at 13:06
  • Consider a pointer-to-member-function. These are often stored as more than a single machine word so that they can handle virtual functions. – Managu Aug 25 '11 at 13:47
1

For fun you could use the C output and see if it's more like what you're after:

printf("0x%p");
noelicus
  • 14,468
  • 3
  • 92
  • 111