Search code examples
assemblymasmmasm32irvine32

Exception thrown at 0x00406A09 in Project.exe: 0xC0000005: Access violation executing location 0x00406A09


What can be the cause of this? I am new to assembly (asm) programming, and I am kind of frustrated of what happening in my code because I have been trying to figure it out for hours.

.data
stringInput BYTE 21 dup (0)
wrongInput BYTE "That is incorrect", 0
correctInput BYTE "That is correct you win", 0
inputSize = 20

.code
push EDX
mov EDX, OFFSET stringInput
mov ECX, inputSize
call readString

loopWord:
mov AL, [ESI]
mov BL, [EDX]
cmp AL, 0
jne loopWord2
cmp BL, 0
jne loopWord2
jmp loopWord4

loopWord2:
inc ESI                                 ;point to the next
inc EDX                                 ;point to next element
cmp AL, BL                              ;is the letter equals?
je loopWord                             ;IF EQUAL loop again
jne loopWord3                           ;not equal go out
pop EDX

loopWord3:
mov EDX, OFFSET wrongInput
jmp WordFinish

loopWord4:
mov EDX, OFFSET correctInput
jmp WordFinish


WordFinish:
call WriteString
RET                                 ;the exception is thrown here 
WordMatching ENDP

I am pretty sure the code is working, it runs properly until the return part. PS: i still have codes other than this, in which the wordMatching PROC will be called.


Solution

  • Put a breakpoint at the start of the code (before executing push EDX), note down the stack address esp plus value in stack (return address to caller).

    Then put a breakpoint at ret. Run the code. Check the esp.

    (you don't ever execute pop EDX, you have it in code, but it is behind pair je + jne, so actually unreachable).

    About the logic of compare, you can simplify it a lot:

    .code
        push EDX
        mov EDX, OFFSET stringInput
        mov ECX, inputSize
        call readString
    
        mov   EBX, OFFSET wrongInput
    loopWord:
        mov   AL, [ESI]
        cmp   AL, [EDX]
        jne   loopWord_wrongInput ; first difference -> wrongInput
        inc   ESI
        inc   EDX
        test  AL,AL
        jnz   loopWord    ; until 0 is found in both strings
    ; here is the branch for correct word
        mov   EBX, OFFSET correctInput ; no difference -> switch result string
    loopWord_wrongInput:
        ; display result string
        mov   EDX,EBX
        call  WriteString
        pop   EDX           ; your missing "pop EDX" fixed here
        ret
    

    edit: I forgot to increment esi/edx in first version, fixed now.