5

I'm just curious if there is any correlation between the length of the address of a variable (pointer) on stack and heap. On many occasions I have seen that those regarding stack variables are usually longer when compared to heap. For example consider the following simple test:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int i = 0;
    int *j = malloc(sizeof(int)); *j = 0;

    printf("&i = %p\n j = %p\n", &i, j);

    free(j);
    return 0;
}

output:

&i = 0x7fffe9c7fa5c
 j = 0x100e010

These results are obtained in linux using gcc; could this be OS/compiler dependent?

mmirzadeh
  • 6,893
  • 8
  • 36
  • 47
  • Not 100% sure, but I would assume that it's CPU/OS/Compiler specific in that order. Also, you're likely not even seeing a physical address. Also, the heap grows up and the stack grows down, so the address of a stack variable being way lower makes sense. – Corbin Mar 25 '12 at 04:29

2 Answers2

2

The results depend on positions of the heap(s) and stack(s) in the address space of the program. These are determined by linker and processor architecture.

Due to ASLR, the exact numbers should be random on modern systems.

Nevertheless, heaps will usually grow upwards, and stacks downwards. Additionally, for performance and memory management reasons, both heaps and stacks will always start on page boundaries.

phihag
  • 278,196
  • 72
  • 453
  • 469
2

I believe it's because of the physical parts of the memory which we decide that they're called stack and heap. Since they start at opposite ends and grow towards the middle, it makes sense that one is lower and the other higher. It would be interesting to see what happens if you allocate 2 consecutive vars on the stack and 2 consecutive ones on the heap. This would help see which way the stack and heap grow. Actually I think for this to work you need to make a new stack frame (a new method) and allocate the second vars there, otherwise you remain in the same stack frame.

Adrian
  • 5,603
  • 8
  • 53
  • 85
  • For a normal userspace program, the address space has nothing to do with physical memory addresses. Otherwise, an unprivileged process could start a DoS attack by allocating some specific physical memory, and thereby prevent another process from allocating the same memory address. It's all virtual. – phihag Mar 25 '12 at 04:51
  • It might be physical or virtual memory, depending on your system. Anyway, starting at both ends and growing towards the middle, gives you maximum flexibility in using all available space. – Bo Persson Mar 25 '12 at 08:45