分段问题NASM

时间:2015-04-30 01:12:02

标签: nasm

我正致力于将c程序转换为NASM,并且在程序运行后我遇到了分段错误的问题。它会做它应该做的事情,但会在它结束时提供分段错误消息。

代码是:

segment .data

out_less    db "Z is less than 20.", 10, 0
out_greater    db "Z is greater than 20.", 10, 0
out_equal    db "Z is equal to 20! Yeah Z!", 10, 0

segment .bss

segment .text

global     main
extern printf
ret
main:

    mov    eax, 10
    mov    ebx, 12

    mov    ecx, eax

    add    ecx, ebx    ;set c (ecx reserved)

    mov    eax, 3
    mov    ebx, ecx
    sub    ebx, eax    ;set f (ebx reserved)

    mov    eax, 12
    mul    ecx
    add    ecx, 10        ;(a+b*c) (ecx reserved)

    mov    eax, 6
    mul    ebx
    mov    eax, 3
    sub    eax, ebx
    mov    ebx, eax    ;(d-e*f) (ebx reserved) reassign to ebx to keep eax open for manipulation

    mov    eax, ecx
    div    ebx
    mov    ecx, eax
    add    ecx, 1        ;(a+b*c)/(d-e*f) + 1

    cmp    ecx, 20
    jl    less
    jg    greater
    je    equal

mov    eax, 0
ret

less:

    push    out_less
    call    printf
    ret
    jmp    end

greater:

    push    out_greater
    call    printf
    ret
    jmp    end

equal:

    push    out_equal
    call    printf
    ret
    jmp     end

end:

    mov    eax, 0
    ret

我不确定是什么导致了这个错误,因为该程序确实能够正常运行任何想法?

谢谢!

1 个答案:

答案 0 :(得分:0)

更新 - 这似乎有效:

segment .data

out_less     db "Z is less than 20.", 10, 0
out_greater  db "Z is greater than 20.", 10, 0
out_equal    db "Z is equal to 20! Yeah Z!", 10, 0

segment .bss

segment .text

        global  main
        extern  printf

main:
        mov    eax, 10
        mov    ebx, 12
        mov    ecx, eax
        add    ecx, ebx    ;set c (ecx reserved)
        mov    eax, 3
        mov    ebx, ecx
        sub    ebx, eax    ;set f (ebx reserved)
        mov    eax, 12
        mul    ecx
        add    ecx, 10     ;(a+b*c) (ecx reserved)
        mov    eax, 6
        mul    ebx
        mov    eax, 3
        sub    eax, ebx
        mov    ebx, eax    ;(d-e*f) (ebx reserved) reassign to ebx to keep eax open for manipulation
        mov    eax, ecx
        div    ebx
        mov    ecx, eax
        add    ecx, 1      ;(a+b*c)/(d-e*f) + 1
        cmp    ecx, 20
        jl    less
        jg    greater
        jmp   equal

less:
        push    out_less
        call    printf
        add     esp,4
        jmp     exit

greater:
        push    out_greater
        call    printf
        add     esp,4
        jmp     exit

equal:
        push    out_equal
        call    printf
        add     esp,4
exit:
        mov    eax, 0
        ret

        end