Calling Malloc from Assembly Language
It's a pretty straightforward function: pass the number of BYTES you
want as the only parameter, in rdi. "call malloc." You'll get back a
pointer to the allocated bytes returned in rax. To clean up the space
afterwards, copy the pointer over to rdi, and "call free" (I'm leaving
off the free below, because you need the stack to do that properly).
Here's a complete example of assembly memory access. I call malloc to
get 40 bytes of space. malloc returns the starting address of this
space in rax (the 64-bit version of eax). That is, the rax register
is acting like a pointer. I can then read and write from the
pointed-to memory using the usual assembly bracket syntax:
mov edi, 40
extern malloc
call malloc
mov ecx,7
mov [rax],ecx
mov edx,[rax]
mov eax,edx
ret
Rather than copy via the ecx register, you can specify you want a
32-bit memory write and read using "DWORD" in front of the brackets,
like this:
mov edi, 40; malloc's first (and only) parameter: number of bytes to allocate
extern malloc
call malloc
; on return, rax points to our newly-allocated memory
mov DWORD [rax],7; write constant into memory
mov eax,DWORD [rax]; read it back from memory
ret