Assembly Language [MASM] Exception Thrown Error

1

This is my MASM code:

.data
  promptMonth BYTE "Enter month ", 0
  promptDay BYTE "Enter day ", 0
  promptYear BYTE "Enter year ", 0
.code
  main PROC
  p1:
    mov edx, OFFSET promptMonth
    call WriteString
    call ReadInt
    mov ebp, eax

  p2:
    mov edx, OFFSET promptDay
    call WriteString
    call ReadInt
    mov esp, eax

  p3:
    mov edx, OFFSET promptYear
    call WriteString
    call ReadInt
    mov edi, eax
  main ENDP       ; Added by edit

For some reason, when the code gets to the "WriteString" function at in p3, I get an error

Exception thrown at 0x00403687 in Project.exe: 0xC0000005:
Access violation accessing location 0x00000000".

I don't understand why, because p1 and p2 run perfectly fine and they're almost the same code as p3.

assembly
x86
irvine32
asked on Stack Overflow Oct 31, 2018 by cplusalex • edited Nov 2, 2018 by Govind Parmar

2 Answers

1

esp is the stack pointer register. On x86, when you call a function, the stack is used for passing parameters and the return address.

When you execute mov esp, eax you are setting the stack pointer to be whatever is returned from ReadInt (which, from its name, I guess is a user-supplied value), which you gave as 0.

The exception code 0xC0000005 is an access violation because the call WriteString instruction tried to put the return address from your calling code into location 0x00000000, which is a null pointer.

Solution: to store the return value from the call to ReadInt, use a register other than esp.

Also, unless you know that you aren't using the designated frame pointer register (ebp) for its intended purpose, you shouldn't use that as a general-purpose register either.

answered on Stack Overflow Oct 31, 2018 by Govind Parmar • edited Oct 31, 2018 by Govind Parmar
0

You are messing up the Stack Pointer with the instruction

mov esp, eax 

Why do you even do that?
Putting the return value in EAX to the stack pointer is a really bad idea.

The first attempt to put EAX to EBP is useless, at best, so it doesn't have any effect so far.

But replacing the Stack Pointer ESP with a return value does mess up everything.

Don't do that!
It's no surprise that the program crashes afterwards (@p3).
So, to fix your program, do the following:

Remove

mov ebp, eax

and

mov esp, eax

from your code.
This should fix your major problems.

The last one

mov edi, eax

doesn't affect the program flow, so you can do as you want.

answered on Stack Overflow Oct 31, 2018 by zx485 • edited Oct 31, 2018 by zx485

User contributions licensed under CC BY-SA 3.0