Home > database >  Why does my variable on the heap sometimes have a higher address than a stack variable
Why does my variable on the heap sometimes have a higher address than a stack variable

Time:12-28

I’m running this code to get the memory address of a stack variable and a heap variable

int main() 
{
    int stack_var = 5;
    int *heap_var_ptr = (int*) malloc(4);

    printf("stack_var is at adress %x\n", &stack_var);
    printf("heap_var is at adress  %x\n", heap_var_ptr);

}

Output:

stack_var is at adress 41a13efc
heap_var is at adress  b09ec2a0

Sometimes the heap variable has a higher adress than my stack variable. Why does this happen I thought the stack starts at a high memory adress and the heap at a low memory adress?

memory layout

My os is popOs

CodePudding user response:

Your C implementation has 64-bit pointers and 32-bit unsigned int, and %x is for unsigned int. With %x, your C implementation is printing only the low 32 bits of the pointers.

Additionally, the behavior of printing a pointer with %x is not defined by the C standard.

To print a pointer properly, convert it to void * and print it with %p:

printf("stack_var is at adress %p\n", (void *) &stack_var);
printf("heap_var is at adress  %p\n", (void *) heap_var_ptr);
  •  Tags:  
  • c
  • Related