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.
Syntax: ptr = (cast-type*) malloc(byte-size) For Example: ptr = (int*) malloc(100 * sizeof(int)); Since the size of int is 4 bytes, this statement will allocate 400 bytes of memory.
The function MALLOC() allocates an area of memory and returns the address of the start of that area. The argument to the function is an integer specifying the amount of memory to be allocated, in bytes. If successful, it returns a pointer to the first item of the region; otherwise, it returns an integer 0.
Malloc will return NULL when the kernel/system lib are certain that no memory can be allocated.
The free() function is used to deallocate memory while it is allocated using malloc(), calloc() and realloc(). The syntax of the free is simple. We simply use free with the pointer. Then it can clean up the memory.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With