1
votes

I was trying to create a for loop in assembly to print out all integers from 0 to N-1. For some reason it breaks and creates an infinite loop. Any ideas why? I am using visual studio 2013 masm

.data
x           DWORD   0
y           DWORD   0


.code
    main:nop
        invoke version
        invoke readInteger
        add x, eax
        cmp eax, y
        je done

    increase:
        invoke writeInteger, y
        inc y
        cmp y, eax
        jg increase

    done:
        invoke writeInteger, x

        invoke ExitProcess,0

    end main
1
Use VS's debugger to single-step and watch registers, then you will know why. But probably writeInteger clobbers eax, which is normal for most calling conventions. - Peter Cordes

1 Answers

2
votes

writeInteger will destroy the contents of EAX and so you can't readily use it in cmp y, eax

Even with that corrected will the loop not work because you need to go back to increase when the y variable is less than x

Because you start y at zero and increment it, all numbers involved will (need to) be positive

If the input is zero, you should display nothing since the input expresses a count!

Putting all together, this is a solution:

 invoke   readInteger
 test     eax, eax
 jz       exitNow
 mov      x, eax                ;x=[1,2GB-1]
increase:
 invoke   writeInteger, y
 inc      y
 mov      eax, x
 cmp      y, eax
 jne      increase
exitNow:
 invoke   ExitProcess,0