Why won't my array properly print?

0

I have a DumpArray procedure that won't properly print out the array. I get this error: Unhandled exception at 0x0040107d in Project.exe: 0xC0000005: Access violation reading location 0x00000006.

At the procedure of DumpArray, more specifically at mov eax,[esi]

INCLUDE Irvine32.inc
.data
     arrayDW SDWORD 5,6,7,3,5,3    ;array

.code
     main PROC
          mov esi, OFFSET arrayDW       ;ESI points arrayDW
          mov ecx, LENGTHOF arrayDW     ;ECX = array count
          call Bubblesort               ;sorts arrayDW
          call DumpArray                ;print array

         exit
     main ENDP

    DumpArray PROC
          push esi
          push ecx
          push eax
          L1:
               mov eax,[esi]
               call WriteInt
               add esi, 4
               loop L1

               call Crlf
               pop esi
               pop ecx
               pop eax
               ret
     DumpArray ENDP

END main

assembly
masm
irvine32
asked on Stack Overflow Apr 18, 2014 by (unknown user) • edited Dec 17, 2015 by rkhb

1 Answer

0

It's in the Bubblesort procedure: ESI points already to the right memory location in arrayDW. The command mov eax, arrayDW[esi] fetches the value from ESI plus memory location of arrayDW - far away from the correct memory location.

I corrected your code ;-):

INCLUDE Irvine32.inc

.data
     arrayDW SDWORD 5,6,7,3,5,3    ;array

.code
     main PROC
          mov esi, OFFSET arrayDW       ;ESI points arrayDW
          mov ecx, LENGTHOF arrayDW     ;ECX = array count
          call Bubblesort               ;sorts arrayDW
          call DumpArray                ;print array

         exit
     main ENDP

    DumpArray PROC USES esi ecx eax
          L1:
               mov eax,[esi]
               call WriteInt
               add esi, 4
               loop L1

               call Crlf
               ret
     DumpArray ENDP

Bubblesort PROC USES esi ecx

          dec ecx

          L1:
               push ecx                 ;save outer loop count
               mov esi, OFFSET arrayDW         ;point to first value in the array was {mov esi, arrayDW}

          L2:
               mov eax, [esi]       ; get array value, eax is the comparer
               cmp [esi+4], eax     ; compare current value with the next value
               jg L3               ; if [ESI=eax] <= [ESI+4], do not exchange
               xchg eax, [esi+4]   ; exchange the pair since [ESI=eax] > [ESI+4]
               mov [esi], eax       ; place the higher value

          L3:
               add esi, 4        ;move both pointers foward
               loop L2           ; looping inner loop

               pop ecx           ;retrieve outer loop count
               loop L1           ; else repeat outer loop

               ret
    Bubblesort ENDP


END main
answered on Stack Overflow Apr 18, 2014 by rkhb

User contributions licensed under CC BY-SA 3.0