【发布时间】:2011-12-15 11:09:28
【问题描述】:
我正在尝试在汇编代码(NASM,64 位)中使用 malloc 和 free。
我试图 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(如果需要的话)
标签: memory-management assembly x86-64 nasm