2014-02-15 52 views
0

以下代碼旨在查找小於1000的3或5的倍數的所有數字的總和(項目歐拉第一個問題)。NASM x86 Segfault

但是,當我執行它時會出現分段錯誤。 我有一種感覺,它可能與我的檢查功能返回後有什麼關係,我將ebx從堆棧中彈出,然後將8加入esp來恢復堆棧幀。這是真的,如果是這樣,我能做些什麼來解決它?

section .data 
section .text 
msg: db "%d", 0 

global main 
extern printf 

main: 

mov ebx, 0 
mov ecx, 0 
;MAINLOOP 
loopstart: 
    inc ebx   
    cmp ebx, 999  ;check if we are done 
    je done   ;if we are, exit 
    push 3 
    push ebx  ;otherwise, check if our number is a multiple of 3 
    call check 
    pop ebx 
    add esp, 8   ;fix stack pointer 
    cmp eax, 1  ;if it is a multiple, add it to our sum 
    je true 
    push 5 
    push ebx 
    call check  ;otherwise check if multiple of 5 
    pop ebx 
    add esp, 8 
    cmp eax, 1 
    je true   ;if it is, add it to our sum 
    jmp loopstart 

true: 
    add ecx, ebx 
    jmp loopstart 

done: 
    push ecx 
    push msg 
    call printf 
    add esp, 8 
    ret 


check: 
    push ebp 
    mov ebp, esp 

    mov eax, [ebp+8]  
    mov ebx, [ebp+12] 
    mov edx, 0 
    div ebx 

    cmp edx, 0 
    je multiple 
    mov eax, 0 

    pop ebp 
    mov esp, ebp 
    ret 

    multiple: 
     mov eax, 1 

     pop ebp 
     mov esp, ebp 
     ret 
+0

剛剛意識到當我調用函數時,我的ecx寄存器也被破壞了。這是什麼導致段錯誤? –

+0

我不這麼認爲。 Ecx僅用作printf的(安全)參數。你應該看到因爲錯誤而打印的垃圾。 BTW。你在用什麼調試器? (GDB有stepi和nexti來貫穿機器指令) –

回答

1

我有固定的問題 錯誤是在我的檢查功能,我用

pop ebp 
mov esp, ebp 

應該已經

mov esp, ebp 
pop ebp 

我相信也有一些其他錯誤與恢復堆棧框架等。 這裏是完整的工作代碼:

section .data 
section .text 
msg: db "%d", 0 
global main 
extern printf 

main: 

mov ebx, 0 
mov ecx, 0 

loopstart: 

inc ebx 
cmp ebx, 1000 
je done 
push ecx 
push ebx 
push 3 
call check 
add esp, 4 
pop ebx 
pop ecx 
cmp eax, 1 
je true 
push ecx 
push ebx 
push 5 
call check 
add esp, 4 
pop ebx 
pop ecx 
cmp eax, 1 
je true 
jmp loopstart 

true: 
add ecx, ebx 
jmp loopstart 

done: 
push ecx 
push msg 
call printf 
add esp, 8 
ret 

check: 

    push ebp 
    mov ebp, esp 

    mov eax, [ebp+12] 
    mov ebx, [ebp+8] 
    mov edx, 0 
    div ebx 

    cmp edx, 0 
    je multiple 
    mov eax, 0 

    mov esp, ebp 
    pop ebp 
    ret 

    multiple: 
     mov eax, 1 
     mov esp, ebp 
     pop ebp 
     ret