Search code examples
linuxassemblyx86glibcatt

x86 Assembly: Calling malloc does not place the pointer to the allocated memory in the EAX register


I am trying to allocate 40 bytes of space in memory through calling the external C command malloc in x86 Assembly (AT&T/Intel syntax). However, when I debug my program, the EAX register has not changed after the malloc command is called (from my understanding, the procedure to use malloc is to put the number of bytes you want to allocate in the EDI register and then executing call malloc to put the pointer to the block of memory allocated in the EAX register). Below is my x86 Assembly code:

.extern malloc

.text
.global main
main:
    movl %esp, %ebp #for correct debugging
    # write your code here
    xorl  %eax, %eax
    
    movl $40, %edi
    call malloc
    
    ret

I am using 32-bit convention (not 64-bit) on Linux.

Compilation command:

gcc -m32 -Wall -g -c -o program.o program.s

Solution

  • call malloc
    

    where's my push?

    push %edi
    call malloc
    add  %esp, 4 ; caller cleans up the stack
    

    So they're telling me that a modern glibc is now imposing an byte stack alignment. I'm not in a position to confirm this, but you've just gotta do it. Would look like this now:

    sub  %esp, 8
    push %edi
    call malloc
    add  %esp, 12 ; caller cleans up the stack