Search code examples
assemblyx86masmirvine32greatest-common-divisor

8086 Assembly Language Program to find GCD of two numbers


Right when it hits " Ret 8" my program stops working. Would anyone be able to tell me why?

Find the GCD of 2 numbers inputted by the user. Keeps looping around till you stop it.

Thanks in advance

INCLUDE irvine32.inc

.data

    msg1 byte " Enter first number", 0ah, 0dh,0
    msg2 byte " Enter second number",0ah, 0dh,0
    msg3 byte " GCD is ",0ah,0dh,0
    ValA DWORD ?
    ValB DWORD ?

.code

main PROC

     start:
            mov edx, offset msg1
            call WriteString
            call ReadDec
            mov ValA,eax



            mov edx, offset msg2
            call WriteString
            call ReadDec
            mov ValB,eax

            mov eax,DWORD ptr[ValA]
            mov ebx,DWORD ptr[ValB]
            push ValB
            push ValA
            call CalcGcd
            call DumpRegs
            call start

    exit
    main ENDP


CalcGcd PROC

        push ebp
        mov ebp, esp
        xor edx,edx
        mov eax, [ebp+8]
        mov ebx, [ebp+12]

    L1:
        cmp eax,ebx
        JE DONE
        JB EXCH

    L2:
        div ebx
        cmp edx,0
        JE DONE
        mov eax,ebx
        mov ebx,edx
        JMP L1

    EXCH:
        XCHG eax,ebx
        JMP L1

    DONE:
        mov eax,ebx
        mov edx, offset msg3
        call writestring
        call writedec
        ret 8



    CalcGcd ENDP
    END main

Solution

  • The code is missing a pop ebp just before the return. The call start will loop over and over until the program runs out of stack space.