Memory management 访问malloc';汇编中的d存储器

Memory management 访问malloc';汇编中的d存储器,memory-management,assembly,malloc,x86-64,nasm,Memory Management,Assembly,Malloc,X86 64,Nasm,我试图访问我在汇编中malloced的内存,但我不断地重复出现segfault错误。在下面的代码中我做错了什么,我确信它很简单,但我就是看不到 编辑:我正在使用64位NASM程序集 ; Allocate room for 8 integers mov r8, 8 mov rdi, r8 imul rdi, 8 ; Multiply by 8 (8 bytes per entry in 64bit) xor rax, rax call malloc add rsp, 8 test rax, rax

我试图访问我在汇编中malloced的内存,但我不断地重复出现segfault错误。在下面的代码中我做错了什么,我确信它很简单,但我就是看不到

编辑:我正在使用64位NASM程序集

; Allocate room for 8 integers
mov r8, 8
mov rdi, r8
imul rdi, 8 ; Multiply by 8 (8 bytes per entry in 64bit)
xor rax, rax
call malloc
add rsp, 8
test rax, rax
jz malloc_failure
mov r8, rsp

; r8 now = base of array

; Set the first element to be 100
mov r9, 0
add r9, r8
mov qword [r9], 100

malloc_failure:
deallocate_start:
dealloc_1:
mov rdi, r8
xor rax, rax
call free
add rsp, 8
deallocate_end:
call os_return      ; return to operating system
还有断层(不是很有趣…)


啊。为什么我使用rsp而不是rax。真是个白痴/在我的电脑屏幕前呆了一天太久了。谢谢你有调试器吗?
matrix05% ./arr5
Segmentation fault
mov r8, 8
mov rdi, r8
imul rdi, 8
xor rax, rax
call malloc
add rsp, 8       ;; here we _add_ 8 bytes to the stack pointer
                 ;; this is equivalent to _popping_ off the stack
                 ;; remember, the x86 stack grows down!
test rax, rax    ;; rax is indeed where the return value is..... but:
jz malloc_failure
mov r8, rsp      ;; we overwrite r8 with the stack pointer (why??)

; r8 now = base of array ;; no it's not

mov r9, 0
add r9, r8       ;; r9 = r8 = stack pointer
mov qword [r9], 100  ;; we now write 100 to the current stack pointer.
                 ;; The stack pointer initially (on entry to the function)
                 ;; pointed to a return address; where exactly are you overwriting?

malloc_failure:
deallocate_start:
dealloc_1:
mov rdi, r8
xor rax, rax
call free
add rsp, 8       ;; we pop from the stack pointer _again_. I do hope there's a sub rsp, 16 at the top...
deallocate_end:
call os_return      ; return to operating system (and probably crash because our stack is FUBAR'd)