I am trying to use dynamic allocation in assembly under macosX, and I have encountered a rather strange behavior while calling _malloc
from the C library.
My final goal would be to allocate something like 10 bytes in memory, but when writing data outside of the allocated chunk, the program doesn't segfault.
Maybe I don't understand how _malloc
works.
This is the test code I wrote. I tried first to push the size on the stack as Christopher Swenson seems to do. Then I read this post that seems to say that the size should be in rdi
. As the latter is more recent, I assumed it was also the most right.
extern _malloc ;; malloc from the C library
section .text
global _start
_start:
xor rdi, rdi
mov rdi, 10 ;; I try to allocate 10 bytes
call _malloc ;; The address should be in rax
mov qword [rax], 1 ;; writing some data where it is supposed to work
add rax, 11 ;; going outside the allocated chunk
mov qword [rax], 1 ;; writing some data where it is not supposed to work
mov rax, 0x2000001
mov rdi, 0
syscall
For simplicity purpose, I don't test rax
, assuming it is not NULL
.
I compiled with :
$ nasm -f macho64 -o test.o test.asm
$ gcc -e _start test.o -lc -m64 -o a.out -Wl,-no_pie
Could someone please explain how I don't use _malloc
properly or why writing outside the allocated chunk does not segfault ?
When you allocate memory with malloc
and the allocation succeeds, you are guaranteed to have that memory you allocated be accessible. However, there is no guarantee that other memory is inaccessible. It's just not guaranteed to be accessible. So do not rely on that.
In practice, malloc
asks the operating system for large chunks of memory at a time and then parcels these chunks out to the various small allocations you make. So it's very common to see that there's more memory accessible than you allocated. However, that memory must not be used, it doesn't belong to your allocation. Instead, malloc
is likely to give that memory to future allocations. It may also be used for other purposes, such as bookkeeping. So don't access it.