Note that there are some explanatory texts on larger screens.

plurals
  1. POMalloc and Free multiple arrays in assembly
    text
    copied!<p>I'm trying to experiment with malloc and free in assembly code (NASM, 64 bit).</p> <p>I have tried to malloc two arrays, each with space for 2 64 bit numbers. Now I would like to be able to write to their values (not sure if/how accessing them will work exactly) and then at the end of the whole program or in the case of an error <strong>at any point</strong>, free the memory.</p> <p>What I have now works fine if there is one array but as soon as I add another, it fails on the first attempt to deallocate any memory :(</p> <p>My code is currently the following:</p> <pre><code>extern printf, malloc, free LINUX equ 80H ; interupt number for entering Linux kernel EXIT equ 60 ; Linux system call 1 i.e. exit () segment .text global main main: push dword 16 ; allocate 2 64 bit numbers call malloc add rsp, 4 ; Undo the push test rax, rax ; Check for malloc failure jz malloc_fail mov r11, rax ; Save base pointer for array ; DO SOME CODE/ACCESSES/OPERATIONS HERE push dword 16 ; allocate 2 64 bit numbers call malloc add rsp, 4 ; Undo the push test rax, rax ; Check for malloc failure jz malloc_fail mov r12, rax ; Save base pointer for array ; DO SOME CODE/ACCESSES/OPERATIONS HERE malloc_fail: jmp dealloc ; Finish Up, deallocate memory and exit dealloc: dealloc_1: test r11, r11 ; Check that the memory was originally allocated jz dealloc_2 ; If not, try the next block of memory push r11 ; push the address of the base of the array call free ; Free this memory add rsp, 4 dealloc_2: test r12, r12 jz dealloc_end push r12 call free add rsp, 4 dealloc_end: call os_return ; Exit os_return: mov rax, EXIT mov rdi, 0 syscall </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload