繁体   English   中英

如何修复汇编中的“未处理的异常”错误?

[英]How to fix “Unhandled exception” error in assembly?

我编写了一个函数,该函数确定一个值是否为质数。 但是,当我从函数返回时,它会出现错误。
错误消息是

Project.exe中0x00000001处未处理的异常:0xC0000005:执行位置0x00000001的访问冲突。

此函数应返回eax

        push ebp
        mov ebp, esp
        mov eax, [ebp+8]                ; store input value
        mov ecx, [ebp+8]                ; store input value in counter
        sub esp, 4                      ; local variable 
        sub ecx, 1                      ; avoid compare with itself
        cmp eax, 3                      ; compare with 1, 2, 3
        jbe Prime

    L1:
        cmp ecx, 3                      ; when count=3 to stop
        je NotP
        mov edx, 0                      ; clear edx to save remainder
        mov [esp-4], eax                ; save input value
        div ecx                         ; divide number
        cmp edx, 0                      ; check remainder
        je NotP                         ; if remainder=0 then not prime
        jmp Prime
        loop L1
    NotP:
        mov eax, 0
        push eax                        ; if delete this ilne still come up error
        pop ebp
        ret
    Prime:
        mov eax, 1                      
        push eax                        ; if delete this ilne still come up error
        pop ebp
        ret
    isPrime  endp
  mov [esp-4], eax ; save input value 

如果打算使用保留了空间的局部变量,则必须编写:

    mov [esp], eax                ; save input value

或者写:

    mov [ebp-4], eax              ; save input value

正确的序言/结尾是:

    push    ebp
    mov     ebp, esp
    sub     esp, 4                 ; local variable 
    mov     eax, [ebp+8]           ; store input value

    ...

NotP:
    mov     eax, 0
    pop     ebp                    ; remove local variable
    pop     ebp
    ret
Prime:
    mov     eax, 1                      
    pop     ebp                    ; remove local variable
    pop     ebp
    ret
isPrime  endp

  cmp edx, 0 ; check remainder je NotP ; if remainder=0 then not prime jmp Prime loop L1 

发现余数不为零还不足以得出数字为质数! 需要更多测试。 现在,该loop L1指令永远不会执行。
例如,为了测试15,您的第一个除法运算结果为15/14,得出的余数非零,但15不是质数。

 L1: cmp ecx, 3 ; when count=3 to stop je NotP 

循环的顶部也不正确! 考虑测试数字7。
一阶除法是7/6并且有余数,因此循环必须继续
二阶除法是7/5并且有余数,因此循环必须继续
三等分是7/4并且有余数,因此循环必须继续
您无需再尝试除法并得出“非质数”的结论,但是7绝对是质数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM