【发布时间】:2014-02-15 05:15:24
【问题描述】:
以下代码用于查找小于 1000 且是 3 或 5 的倍数的所有数字的总和。(欧拉计划第一个问题)。
但是,当我执行它时会出现分段错误。 我感觉这可能与从我的检查函数返回后有关,我将 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
【问题讨论】:
-
刚刚意识到当我调用函数时,我的 ecx 寄存器也被破坏了。这是导致段错误的原因吗?
-
我不这么认为。 Ecx 仅用作 printf 的(安全)参数。由于该错误,您应该只看到打印的垃圾。顺便提一句。您正在使用什么调试器? (GDB 有 stepi 和 nexti 来单步执行机器指令)
标签: assembly x86 segmentation-fault nasm