Joe Caruso
Joe Caruso

Reputation: 1374

Access violation in Masm when accessing memory offset

I'm trying to to a selection sort in x86 assembly and I'm getting an access error violation when I try to use a variable to access an offset of an array.

.data
array BYTE "fairy tale"
count = ($ - array)
minIndex BYTE ?

.code
_main PROC

mov eax, 0                          
mov ebx, 0                          

mov ecx, count                      ; move array count to counter register
dec ecx                             ; decrease counter
lea esi, array


mov bl, 0                           ; i = 0
L1:
push ecx        


mov minIndex, bl                    ; minIndex = i
mov al, minIndex[esi]               ; THIS GIVES THE ERROR

; rest of code...

ret

_main ENDP

END _main

There are no build errors, only the access violation at run time. Are you not allowed to do such an operation in MASM? Is there a workaround?

Upvotes: 0

Views: 411

Answers (1)

Michael
Michael

Reputation: 58427

mov al, minIndex[esi]

If you think that will take the value of minIndex and use that to offset esi in the read operation, then you're incorrect. What it will do is use the address of minIndex.

You can change your code to:

movzx eax,byte ptr minIndex  ; zero-extend the byte at minIndex into eax..
mov al,[esi+eax]             ; ..and use that as an offset into the array

Upvotes: 2

Related Questions