【问题标题】:NASM x86 SegfaultNASM x86 段错误
【发布时间】: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


【解决方案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

【讨论】:

    猜你喜欢
    • 2012-11-10
    • 1970-01-01
    • 1970-01-01
    • 2016-09-10
    • 2014-01-31
    • 2013-07-24
    • 2015-01-09
    • 2012-06-26
    • 2012-05-26
    相关资源
    最近更新 更多