Using memory returned by call to malloc in NASM
I'm using the nasm compiler to compile my code into an object file then calling gcc's linker to link that object file to create the final executable. This means that I have access to the C开发者_如何学编程's runtime libraries.
I need to do dynamic memory allocation so I'm making a call to malloc as follows
push 20 ;push amount of bytes malloc should allocate
call _malloc ;call malloc
add esp,4 ;undo push
The address of the memory allocated is returned in the eax register, but then how to I use the address to initialize that position with values?
The intention of my program is to have the user specify how many numbers they want to enter, then create space dynamically for each number. Ideally I'm hoping to create an array that matches the exact size specified by the user and be able to iterate through this array.
After you have allocated memory with malloc
, the value of eax
is just a pointer you can use. For example, to write values to the first two 32-bit int
s there, you can do:
mov dword ptr [eax], 0
mov dword ptr [eax + 4], 1
push 20 ; push amount of bytes malloc should allocate
call _malloc ; call malloc
test eax, eax ; check if the malloc failed
jz fail_exit ;
add esp,4 ; undo push
mov [eax], dword 0xD41 ; 'A\n'
Anyway, I suggest you to take a look at this tutorial, it has pretty interesting stuff:
This program prints "Hello World", allocates some memory using malloc, uses that memory to write 10 letters of the alphabet on the screen (using printf), frees the memory, and returns.
精彩评论