tags:

views:

309

answers:

2

Can someone explain the following strange behavior?

I run the following program on a 64-bit Intel platform:

include <stdio.h>
#include <stdint.h>

int main(void)
{
  int x;
  int *ptr = &x;

  printf("ptr = %p\n", ptr);
  printf("sizeof(ptr) = %d\n", sizeof(ptr));

  int64_t i1 = (int64_t) ptr;
  printf("i1 = 0x%x\n", i1);
  printf("sizeof(i1) = %d\n", sizeof(i1));

  return 0;
}

This program produces the following output:

ptr = 0x7fbfffdf2c
sizeof(ptr) = 8
i1 = 0xbfffdf2c
sizeof(i1) = 8

Can anyone explain why i1 contains only the least significant 32 bits of ptr? (Note that it is missing 0x7f).

Compiler: gcc version 3.4.6 20060404 (Red Hat 3.4.6-9)
OS: Linux scream 2.6.9-67.ELsmp #1 SMP Wed Nov 7 13:56:44 EST 2007 x86_64 x86_64 x86_64 GNU/Linux
Processor: Intel(R) Xeon(R) CPU E5430  @ 2.66GHz
+12  A: 

It hasn't gone anywhere .. your print statement is wrong. Try this:

printf("i1 = 0x%lx\n", i1);
eduffy
Duh! Thanks very much.
Cayle Spandon
+2  A: 

First, you are casting the pointer to a signed integer - that's wrong - pointers are unsigned. Then you are printing the 64-bit value with %x format modifier - that expects 32-bit value on the stack. Try compiling with -Wall -pedantic and let gcc complain.

Nikolai N Fetissov