Search code examples
assemblyx86masm

Access Violation MASM x86 Assembly


I am working on a project and I am currently getting an Access Violation in one of my lines. I was wondering if I could get a second opinion on what is wrong. Here is my code (Note, I get the error during runtime, but it does build):

.data
BlueTextOnGray = blue + (lightGray * 16)
DefaultColor = lightGray + (black * 16)
arrayD SDWORD 12345678h,1A4B2000h,3434h,7AB9h

fib BYTE 1,2
  BYTE NUMBER_FIBS_TO_COMPUTE dup(0)

prompt  BYTE    "Enter an ending integer: ",0
error   BYTE    "Invalid stopping point! 



.code

main PROC

    mov eax,BlueTextOnGray
    call    SetTextColor
    call    Clrscr          ; Clear the screen
    call    Crlf            ; New line

    mov edx,OFFSET prompt
    call    WriteString
    call    ReadInt         ; Input integer into EAX
    call    Crlf            ; New line

  lea esi, [fib+2]
  mov cl, NUMBER_FIBS_TO_COMPUTE
@@:
  mov al, [esi-2]
  add al, [esi-1]
  mov [esi], al   ;<------------This is where the error occurs
  inc esi
  loop @B

; here print out the results or examine them with debugger

E1: call    Crlf            ; New line
    call    WaitMsg         ; "Press any key..."
    mov eax,DefaultColor
    call    SetTextColor
    call    Clrscr



exit
main ENDP
END main

Is there a rule that I am missing. I have done my research but I cannot seem to find the answer that fits my situation.

Any help would be great! (Also note that I am not done with it so there might be other mistakes.)

Thanks!


Solution

  • Your problem is that, wherever fib points to, which is loaded into esi, that memory page is marked as read-only.

    Generally, an access violation is caused by attempting to write to a memory location that is marked read-only in the GDT. A segmentation fault occurs when you attempt to read from a memory location that your process does not have access to at all.

    As @Jester points out, you're not paying attention to the high order bits in ECX. While you set your loop control value in CL, your loop may run far higher than you intend since ECX is unknown. This would quickly put you into read-only territory in your memory.