Run-Time Check Failure #2 - Stack around the variable 'tempMatrix' was corrupted

1k views Asked by At

I have been trying to run a function that gets a matrix, and rotate it 90 degrees clockwise. For some reason in the first 'for' in the function, 'b' adds 1 after reaching 2 value, after that works fine, but then the matrix is too big and getting that error. Can't understand why it doing additional ++.

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#define ROTATE_MATRIX_SIZE 5

void RotateMatrix90(int matrix[][ROTATE_MATRIX_SIZE]);

int main()
{
    int i, j;
    int matrix[ROTATE_MATRIX_SIZE][ROTATE_MATRIX_SIZE] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25 };

    RotateMatrix90(matrix);

    for (i = 0; i < ROTATE_MATRIX_SIZE; i++)
    {
        for (j = 0; j < ROTATE_MATRIX_SIZE; j++)
        {
            if (matrix[i][j] < 10)
                printf(" ");
            printf("%d ", matrix[i][j]);
        }
        printf("\n");
    }

    getch();
    return 0;
}

void RotateMatrix90(int matrix[][ROTATE_MATRIX_SIZE])
{
    int i, j, a, b, tempMatrix[ROTATE_MATRIX_SIZE][ROTATE_MATRIX_SIZE];
    for (i = 0, a = ROTATE_MATRIX_SIZE; i < ROTATE_MATRIX_SIZE; i++, a--)
    {
        for (j = 0, b = 0; j < ROTATE_MATRIX_SIZE; j++, b++)
            tempMatrix[a][b] = matrix[i][j];
    }
    for (i = 0; i < ROTATE_MATRIX_SIZE; i++)
    {
        for (j = 0; j < ROTATE_MATRIX_SIZE; j++)
            matrix[i][j] = tempMatrix[i][j];
    }
}
1

There are 1 answers

0
Sadique On BEST ANSWER

I believe this line is problematic:

for (i = 0, a = ROTATE_MATRIX_SIZE; i < ROTATE_MATRIX_SIZE; i++, a--)

try this:

for (i = 0, a = ROTATE_MATRIX_SIZE - 1; i < ROTATE_MATRIX_SIZE; i++, a--)

Making a = ROTATE_MATRIX_SIZE is making tempMatrix[a][b] access a location you are not allowed to access hence the error.