Using memory returned by malloc in NASM

I use the nasm compiler to compile my code into an object file, and then the gcc linker is called to link this object file in order to create the final executable. This means that I have access to the C runtime libraries.

I need to do dynamic memory allocation, so I am making a malloc call as follows

push 20 ;push amount of bytes malloc should allocate    
call _malloc ;call malloc
add esp,4 ;undo push

The allocated memory address is returned in the eax register, but how can I use the address to initialize this position with values?

The goal of my program is to indicate how many digits they want to enter, and then dynamically create space for each number. Ideally, I hope to create an array that matches the exact size specified by the user and can iterate through this array.

+5
source share
2 answers
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'

In any case, I suggest you take a look at this tutorial , it has some pretty interesting things:

This program prints "Hello World", allocates some memory using malloc, uses this memory to write 10 letters of the alphabet on the screen (using printf), frees the memory, and returns.

+4
source

malloc eax - , . , 32- int , :

mov dword ptr [eax], 0
mov dword ptr [eax + 4], 1
+3

All Articles