I am learning binary exploitation from "Hacking: The Art of Exploitation". In theory the address of an element of stack should be higher than the address of an element on heap. But in this program I am getting the address of stack_var is lower than that of heap_var. I am using Ubuntu 18.04.2 LTS with AMD Ryzen 5 2500u processor.

#include <stdio.h>

int global_var;
int global_initialized_var = 5;

void function(){
    int stack_var;

    printf("the function's stack_var is at address 0x%08x\n", &stack_var);

int main(){
    int stack_var;
    static int static_initialized_var = 5;
    static int static_var;
    int *heap_var_ptr;

    heap_var_ptr = (int *) malloc(4);

    //These variables are in data segment
    printf("global_initialized_var is at address 0x%08x\n", &global_initialized_var);
    printf("static_initialized_var is at address 0x%08x\n", &static_initialized_var);

    //These variables are in bss segment
    printf("static_var is at address 0x%08x\n", &static_var);
    printf("global_var is at address 0x%08x\n", &global_var);

    //This variable is in heap segment
    printf("heap_var is at address 0x%08x\n", heap_var_ptr);

    //These variables are in stack segment
    printf("stack_var is at address 0x%08x\n", &stack_var);


global_initialized_var is at address 0x91d2f010
static_initialized_var is at address 0x91d2f014
static_var is at address 0x91d2f01c
global_var is at address 0x91d2f020
heap_var is at address 0x9292b260
stack_var is at address 0x242e2bec
the function's stack_var is at address 0x242e2bc4
  • I guess this is to do with ASLR. What's your compiler and what are compiler options? – domen Jul 22 '19 at 8:33
  • @domen It is GNU compiler collection(gcc) and compiled program with gcc memory_segment.c – coder Jul 22 '19 at 8:36
  • 1
    Would you address the compiler warnings first, and then check if your premise still holds? ;) – domen Jul 22 '19 at 8:41
  • @domen Now I am getting stack address higher than heap address. Used %p to print address instead of 0x%08x. – coder Jul 22 '19 at 8:55

As you have spotted, with %p it works as expected.

The explanation at the source of your situation is that %x reads integers (whose size is 4 bytes) out from pointers (whose size is 8 bytes on your architecture). So, you are simply asking printf to read the first 4 bytes of the pointer, neglecting the rest 4. You may change your format to "0x%016lx" to format pointers with leading zeros.

In those cases where the pointer is small enough to fit in 4 bytes, you see them (haphazardly) correctly because the least significant bytes are stored as first due to the fact that your architecture is little-endian.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.