x86 Assembly: Program to sum input values and then average them is crashing after trying to access a memory location that is not accessible


I have a school assignment that has got me stumped. The program is to read in values, pass them into an array, sum the values, and average them.

inputArray  DWORD 100 DUP(?)
elementCnt  DWORD 0
number      DWORD ?
prompt      BYTE  "Enter values. (-1 to quit) ", 0
string      BYTE  40 DUP (?)
resultLbl   BYTE  "The sum is", 0
sum         BYTE  11 DUP (?), 0

_MainProc PROC
    mov  eax, 0                    ; EAX = 0
    lea  ebx, inputArray           ; EBX = [inputArray]
    mov  ecx, elementCnt           ; ECX = 0

    input prompt, string, 40      ; Get input from the user
    atod  string                  ; Convert to decimal, result stored in EAX
    mov   [ebx + (ecx * 4)], eax        ; Move the user input into the array
    add   ecx, 1
    cmp   eax, -1
    jg    getInputs

    mov  eax, 0

    mov  eax, 0                    
    lea  ebx, inputArray           
    mov  ecx, elementCnt          

    push ebx
    push eax
    call sumAndAverage

    mov  eax, 0
_MainProc ENDP

sumAndAverage PROC
    push ebp
    mov  ebp, esp
    push eax

    add  eax, [ebx + ecx] ; <------ CRASHING HERE 
    loop sumValues

    xor  edx, edx
    idiv ecx

    pop  eax
    pop  ebp
sumAndAverage ENDP

I am not the greatest at assembly. It is definitely not my language.

input and prompt are both macros defined in a header named io.h. The section of code that uses them works fine. To be honest, I have an inkling of an idea what might be causing the crash, but I am not sure. The code is crashing because it is trying to access a memory location it’s not allowed to access. This means that something is wrong with my code to read the values from the array.

If someone could explain to me what my problem is without providing a solution, I’d appreciate it.

>Solution :

Taking a look at this section of code:

    add  eax, [ebx + ecx] ; <------ CRASHING HERE 
    loop sumValues

loop decrements ecx. Since ecx is zero when you enter sumAndAverage (you should be able to figure out why this is), ecx becomes negative as you iterate through the loop. This causes the effective address of [ebx + ecx] to go out of bounds. This qualifies as a segmentation fault.

Leave a Reply Cancel reply