Search code examples
cmatrixaccess-violation

Array access violation exception in for loop at index 0


I'm writing a program that needs to build the following matrix:

  • n,m are the number of lines and columns respectively
  • all elements on the last column must be equal to 1
  • all elements on the last row must be equal to 1
  • all other elements must be the last digit of the sum between the element underneath and the element on their right

Here's my function.

void buildMatrix()
{
    // Last row is 1.
    for (unsigned int j = 0; j < m; j++)
        M[n - 1][j] = 1;

    // Last column is 1
    for (unsigned int i = 0; i < n; i++)
        M[i][m - 1] = 1;

    // Other elements are calculated
    for (unsigned int i = n - 2; i >= 0; i--)
        for (unsigned int j = m - 2; j >= 0; j--)
            M[i][j] = (M[i + 1][j] + M[i][j + 1]) % 10;         
}

However, on the last line (M[i][j] = (M[i + 1][j] + M[i][j + 1]) % 10;) it throws me an access violation exception. I cannot for the love of me figure out why.

As an example, for n = 4 and m = 5, my function should be

5 0 0 4 1
5 0 6 3 1
5 4 3 2 1
1 1 1 1 1

It seems the problem occurs when i or j reach zero. if I replace the ">=" with ">" in the last fors, it gives me the following:

0 0 0 0 1
0 0 6 3 1
0 4 3 2 1
1 1 1 1 1

Why is it having problems for the rows and columns of 0?


Solution

  • Unsigned values can't be negative, so the condition i >= 0 is always true.

    If you decrement unsigned i when its value is 0 it becomes UINT_MAX due to unsigned underflow and the loop continues. Trying to access such index throws an exception because it's not only out of array bounds but is also out of the program memory space.

    Personally, I would use a signed int for a loop iterator instead.