我想用malloc和免費的彙編代碼(NASM,64位)實驗。Malloc和免費的多個數組在組裝
我試圖malloc兩個數組,每個都有2個64位數字的空間。現在我想能夠寫入他們的值(不知道是否/如何訪問它們將完全正常工作),然後在整個程序結束時或者在出現錯誤在任何點時釋放內存。
我現在如果有一個數組,但只要我添加另一個,它在第一次嘗試解除分配任何內存無法正常工作:(
我的代碼目前是以下:
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
你複製粘貼失敗:dealloc_2做`test r11,r11`,但它必須是'test r12,r12`(如果需要的話) ) – 2011-12-15 12:36:30