Why Does movl (%eax), %edx Crash After Using Custom malloc_ Implementation in Assembly?

I have implemented a custom memory allocation function using sys_mmap for memory allocation. Here’s my code for the malloc_ function:
malloc_:
pushq %rbp
movq %rsp, %rbp

mov %rdi, %rcx # store size
movl $9, %eax # system call 9: sys_mmap
movq $0, %rdi # start address
movq %rcx, %rsi # size
movl $3, %edx # page flags (PROT_READ | PROT_WRITE)
mov $34, %r10 # mem flags (MAP_PRIVATE | MAP_ANONYMOUS)
movl $-1, %r8d # file descriptor
movl $0, %r9d # offset
syscall

cmp $0, %rax
jg .L1.malloc_exit_ # jump if allocation was successful
mov $0, %rax # set return value to 0 if failed
.L1.malloc_exit_:
popq %rbp
retq
malloc_:
pushq %rbp
movq %rsp, %rbp

mov %rdi, %rcx # store size
movl $9, %eax # system call 9: sys_mmap
movq $0, %rdi # start address
movq %rcx, %rsi # size
movl $3, %edx # page flags (PROT_READ | PROT_WRITE)
mov $34, %r10 # mem flags (MAP_PRIVATE | MAP_ANONYMOUS)
movl $-1, %r8d # file descriptor
movl $0, %r9d # offset
syscall

cmp $0, %rax
jg .L1.malloc_exit_ # jump if allocation was successful
mov $0, %rax # set return value to 0 if failed
.L1.malloc_exit_:
popq %rbp
retq
In my main function, I use malloc_ to allocate memory like this:
.globl main
main:
pushq %rbp
movq %rsp, %rbp

mov $512, %rdi # size to allocate
call malloc_
cmp $0, %rax # check if allocation failed
je exit
// movl (%eax), %edx // <---- causes a crash
mov (%rax), %rdx // <---- works fine

exit:
# Exit code here
.globl main
main:
pushq %rbp
movq %rsp, %rbp

mov $512, %rdi # size to allocate
call malloc_
cmp $0, %rax # check if allocation failed
je exit
// movl (%eax), %edx // <---- causes a crash
mov (%rax), %rdx // <---- works fine

exit:
# Exit code here
The issue I don’t understand is why the line movl (%eax), %edx causes a crash, but using mov (%rax), %rdx works perfectly fine. If I use the system provided malloc function instead, both lines work without issue. What could be causing this behavior with my custom malloc_ function?
0 Replies
No replies yetBe the first to reply to this messageJoin
Want results from more Discord servers?
Add your server