返回时的NASM分段错误

时间:2017-09-30 13:28:28

标签: assembly x86 nasm

我正在创建一个接受两位数字的程序,然后将素数从1打印到两位数字。在我打印完所有素数后,当程序已经退出时,会出现seg故障。如何解决这个问题?提前谢谢。

以下是提供素数的子程序。

;firstLoopBody, this will loop the numbers from 1 to N
;secondLoopBody, this will loop the numbers to be divided from the firstLoopBody
getPrimes:
    mov ebp,esp
    call firstLoopBody

    ret 6

firstLoopBody:
    ;loop the numbers from 1 to N
    mov ax,[ebp+6]
    cmp ax,[ebp+8]
    jne next

    mov eax,4
    mov ebx,1
    mov ecx,exitString
    mov edx,esLen
    int 80h

    ret

next:
    inc word[ebp+6] ;add 1 to the firstLoop
    mov word[ebp+4],1 ;restart the value of secondLoop every getPrimes

secondLoopBody:
    inc word[ebp+4]
    ;check if the secondLoop == firstLoop
    mov ax,[ebp+6]
    cmp ax,[ebp+4]
    je printOne

    mov dx,0
    mov ax,[ebp+6]
    div word[ebp+4]

    cmp dx,0 ;compare the remainder to 0

    jne secondLoopBody ;if the remainder is not zero, loop again
    jmp firstLoopBody ;if equal, go back to the start

printOne:
    call printPrimes;print prime. if the loop has reached its end without breaking, it means that there are no divisible numbers found for the number, therefore making it a prime number
    jmp firstLoopBody

printPrimes:
    sub esp,4 ;to allocate for the characters to be printed
    ;convert to characters
    mov dx,0
    mov ax,[ebp+6]
    mov cx,10
    div cx

    mov [ebp-4],ax
    mov [ebp-2],dx ;-2 = ones, -4 = tens

    add word[ebp-4],30h
    add word[ebp-2],30h

    ;printing
    mov eax,4
    mov ebx,1
    mov ecx,prime
    mov edx,primeLen
    int 80h

    mov eax,4
    mov ebx,1
    lea ecx,[ebp-4]
    mov edx,1
    int 80h

    mov eax,4
    mov ebx,1
    lea ecx,[ebp-2]
    mov edx,1
    int 80h

    mov eax,4
    mov ebx,1
    mov ecx,nl
    mov edx,nlLen
    int 80h

    add esp,4

    ret

0 个答案:

没有答案