What exactly does _malloc do in assembly?

Viewed 30231
public main
main proc near
push    ebp
mov     ebp, esp
and     esp, 0FFFFFFF0h
sub     esp, 30h
mov     dword ptr [esp], 8 ; size
call    _malloc
mov     [esp+2Ch], eax
mov     dword ptr [esp+4], 4
mov     eax, [esp+2Ch]
mov     [esp], eax
call    __start

The code above represents a portion of a large project I am working on. I am trying to reverse this code into C equivalent but I am having difficulty understanding how malloc works.

I am figuring 8 bytes would be the size of the memory being allocated; however, I am not sure about this line.

mov      eax, [esp+2ch] 

What does malloc do to eax?

Furthermore would this be equivalent C code?

int main(void)
{
int *ptr1;
ptr1 = (int *)malloc(sizeof(8));
*ptr1 = 4;
__start(*ptr1);
2 Answers

I'd like to emphasize something that was not mentioned in the other great answer.

How does malloc work internally? What does it do in assembly to create the needed memory?

According to this website, malloc and other memory calls use an operating system API function to allocate and free memory on the heap.

Related