Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 970
Mark Avatar asked Apr 05 '11 03:04

Mark


People also ask

How do I assign a memory to malloc?

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.

What is the type of address returned by the malloc () function?

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.

What is returned by malloc when sufficient memory is not available for allocation?

Malloc will return NULL when the kernel/system lib are certain that no memory can be allocated.

How memory allocated by malloc () function can be deallocated?

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.


1 Answers

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 ints there, you can do:

mov dword ptr [eax], 0
mov dword ptr [eax + 4], 1
like image 96
Jeremiah Willcock Avatar answered Oct 18 '22 05:10

Jeremiah Willcock