Search code examples
arraysexceptionassemblymasmirvine32

MASM x86 Access Violation While Running Loop


I have an array of two-byte integers, which I am populating with random 3 digit numbers, using ESI to walk through the array. I am getting an access violation when I attempt to access the 9th element of the array and store it in ESI.

ARRAYSIZE = 200

.data
list        WORD    ARRAYSIZE   DUP(?)

fillArray PROC
    push    OFFSET list
    mov     esi, [esp] ;GET ADDRESS OF FIRST ELEMENT INTO ESI
    mov     ecx, request ;NUMBER OF ELEMENTS TO BE ADDED

ArrFill:
    ;calculate random 3-digit number, store in eax
    dec     ecx
    mov     [esi], eax ;THIS IS THE LINE THAT THROWS THE EXCEPTION
    sub     esi, 2
    cmp     ecx, 0
    jnz     ArrFill

Exception thrown: Access violation writing location 0x00405FFE (The value of ESI when thrown).

When I change the array to four-byte integers, I also get an access violation for trying to access the 5th element of the array at the same address.


Solution

  • push    OFFSET list
    mov     esi, [esp] ;GET ADDRESS OF FIRST ELEMENT INTO ESI
    

    Why not simply assign the offset to ESI with mov esi, OFFSET list

    mov     [esi], eax ;THIS IS THE LINE THAT THROWS THE EXCEPTION
    

    Since the array contains words you can only write the contents of AX, not EAX! Use mov [esi], ax

    sub     esi, 2
    

    To progress through the array you need to add to the pointer not subtract from it. Use add esi, 2