1

I just executed this code example:

int *i = (int*) malloc( sizeof(int) );
printf( "%p, %p\n", &i , i );

and this is what I got:

0x7fff38fed6a8, 0x10f7010

So I wonder why is the second address shorter than the first one?

Matt
  • 22,721
  • 17
  • 71
  • 112
math
  • 8,514
  • 10
  • 53
  • 61

5 Answers5

5

i is on the stack, while the chunk of memory it points to is in the heap. On your platform these are two very different areas of memory and it just so happens the heap addess is relatively low, numerically, so it has a lot of leading zeroes which are not shown, i.e.

&i = 0x7fff38fed6a8; // stack
 i = 0x0000010f7010; // heap
Paul R
  • 208,748
  • 37
  • 389
  • 560
4

i is an address on the heap, while &i is an address on the stack. The heap and stack occupy different address ranges, so you see different numbers.

The pointers aren't actually different lengths: the shorter one is preceded by zeroes. You are probably running this on a 64-bit machine, so each pointer has 64 bits (16 hex digits).

interjay
  • 107,303
  • 21
  • 270
  • 254
1

There is no requirement that the %p formatting specifier pads the output to any fixed length. So you can't deduce any information about the in-memory "length" of an address from the printed representation. For instance, if you do this:

const void *nada = NULL;

printf("NULL is at %p\n", nada);

You might well see something like this:

NULL is at 0x0

Of course, this doesn't mean that the void * type is magically occupying only 4 bits when the value is NULL, it simply means that when the pointer value was converted to string, leading zeros were omitted.

UPDATE: Mis-read the question's code, I deleted the irrelevant text.

unwind
  • 391,730
  • 64
  • 469
  • 606
1

It is not shorter, just number is smaller. Pointer &i is on stack and i is on heap.

Luka Rahne
  • 10,336
  • 3
  • 34
  • 56
1

In addition to the other answers:

Since you didn't include <stdlib.h> there is a good chance that the compiler incorrectly assumes that malloc returns int rather than void*. This is a possibly severe bug, which you have hidden away with the typecast of malloc's return value. Read this and this.

If int has a different width than the address bus on your specific system, for example on many 16-bit or 64-bit CPUs, you will get incorrect results.

Community
  • 1
  • 1
Lundin
  • 195,001
  • 40
  • 254
  • 396