Goodies
Goodies

Reputation: 4681

C StdLib malloc From (N)ASM

I'm looking to call malloc() from an ASM file. In ASM:

extern malloc

didn't work. I would like to link the CStdLib.

Upvotes: 1

Views: 1704

Answers (1)

Gunner
Gunner

Reputation: 5884

What exactly does "didn't work" mean? You need to do more than just use extern, you need to link against the C Library. The easiest way is to use gcc to link. As you didn't mention if your code is 32 bit or 64, I will go with 32 bit. The process is basically the same for 64 bit.

extern exit, printf, malloc, free

global main

BUFFER_SIZE     equ 27

section .data
fmtstr      db  "%s", 10, 0

section .text
main:

    push    BUFFER_SIZE
    call    malloc
    add     esp, 4 * 1
    mov     esi, eax

    xor     ecx, ecx
    mov     edx, 97

.FillBuffer:
    mov     byte [esi +  ecx], dl
    inc     edx
    inc     ecx
    cmp     ecx, BUFFER_SIZE - 1
    jne     .FillBuffer

    mov     byte [esi + ecx], 0

    push    esi
    push    fmtstr
    call    printf
    add     esp, 4 * 2

    push    esi
    call    free
    add     esp, 4 * 1

    push    0
    call    exit
    add     esp, 4 * 1

and the makefile:

APP=malloctest

all: $(APP) clean

$(APP): $(APP).o    
    gcc -o $(APP) $(APP).o 

$(APP).o: $(APP).asm
    nasm -f elf $(APP).asm 

clean:
    rm $(APP).o 

enter image description here

Upvotes: 2

Related Questions