Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

memory location patterns on stack and heap

Tags:

c

pointers

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?

like image 882
mmirzadeh Avatar asked Oct 09 '22 07:10

mmirzadeh


2 Answers

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.

like image 64
phihag Avatar answered Oct 12 '22 10:10

phihag


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.

like image 21
Adrian Avatar answered Oct 12 '22 10:10

Adrian