title: malloc and free x86 NASM + compiling
body: <p>I have been teaching myself x86 assembly and have been looking at doing basic malloc() and free() calls. I have spent quite a bit of time searching but most examples are for 64-bit or only show the malloc call without the free, etc. I even wrote this in c, then compiled and disassembled it, which helped but gcc adds a lot of other instructions.</p>
  
  <p>Here is a basic example I made of what I was able to figure out, please let me know if this is correct or if there is anything else I should be doing:</p>
  
  <pre><code>global _start
  ; glibc stuff
  extern _malloc, _free
  
  section .data
    err: db "malloc failed!", 10, 0
      .len: equ $ - err
  
  section .bss
    mptr resd 1   ;pointer to begining of malloc'd memory
  
  section .text
  _start:
  
    push 20       ;allocate 20 bytes
    call _malloc  ;call malloc
    add esp, 4    ;clean pushed imm
  
    test eax, eax ;check for malloc error
    jz merror
  
    mov [mptr], eax ;store address
  
    mov byte [eax], 0
    mov byte [eax + 1], 1
  
    push mptr     ;push address
    call _free    ;call free
    add esp, 4    ;clean push
  
  exit:
    mov eax, 0x1
    int 80h
  
  merror:
    mov eax, 0x4
    mov ebx, 0x1
    mov ecx, err
    mov edx, err.len
    int 80h
    jmp exit
  </code></pre>
  
  <p>The second part to my question is compiling it. From what I was able to find I need to link <code>/lib/ld-linux.so.2</code>. So in my makefile I have the following but it errors out:</p>
  
  <pre><code>mem: mem.asm
      nasm -f elf mem.asm
      ld -melf_i386 -lc -I /lib/ld-linux.so.2 mem.o -o mem
  </code></pre>
  
  <p>This is the error I get when trying to compile:</p>
  
  <p><a href="https://i.stack.imgur.com/Ef5Ed.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ef5Ed.png" alt="enter image description here"></a></p>
  
  <p>As I said I am a noob at x86 so if you also have any comments for better ways to do things I would appreciate those too! :)</p>
  
  <p><strong>UPDATE</strong> :</p>
  
  <p>So I went ahead and used gcc and got that to work (without and errors at least):</p>
  
  <pre><code>mem: mem.asm
      nasm -f elf mem.asm
      gcc -m32 mem.o -o mem
  </code></pre>
  
  <p>However when I went to run it it crashed big time:
  <a href="https://i.stack.imgur.com/AeGBV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AeGBV.png" alt="enter image description here"></a></p>
  
  <p>I am clearly doing something wrong with <code>free</code> but as I mentioned, I wasn't positive about my use of <code>malloc</code> and <code>free</code> since I couldn't find any solid examples. Any clues?</p>