Stack overflow when manipulating Bi-dimensional integer array

1

I wrote this C++ program to sort an integer matrix using selection sort. I tried to compile and run the program. But I ran into a stack overflow error and the message also said something about an access violation writing location .

I tried the following steps:

  1. Tried reducing the array size from 50 x 50 to 10 x 10.
  2. Tried heap allocation to the resultant array (using new).
  3. Tried declaring the resultant array as static.
  4. Tried examining the Memory option in Debug Menu for that particular memory location(but couldn't make sense of it).
  5. Tried examining the chkstk.asm file that the IDE automatically opened.

But all these efforts were of no use.

This is the part of the source code involved in the runtime error.

void SelectionSort(int matrix[][10], int rowMax, int colMax)
{
    //Runtime error was pointed over here.

    int smallest, temp, position, count = 0;
    int resultant[10][10];

    for (int row = 0; row < rowMax; row++)
    {
        for (int j = 0; j < rowMax - 1; j++)
        {
            smallest = matrix[row][j];
            position = j;

            for (int k = j + 1; k < rowMax; k++)
            {
                if (matrix[row][k] < smallest)
                {
                    smallest = matrix[row][k];
                    position = k;
                }
            }
            temp = matrix[row][j];
            matrix[row][j] = matrix[row][position];
            matrix[row][position] = temp;
        }

    }
    for (int i = 0; i < rowMax; i++)
        for (int j = 0; j < colMax; j++)
            resultant[i][j] = matrix[j][i];

    if (count == 0)
    {
        SelectionSort(resultant, rowMax, colMax);
        count++;
    }

    else
    {
        std::cout << "The sorted matrix is: " << std::endl;
        for (int i = 0; i < rowMax; i++)
        {
            for (int j = 0; j < colMax; j++)
            {
                std::cout << matrix[i][j] << "  ";
            }
            std::cout << "\n";
                }
        }
}  

These were the messages that were thrown.

Exception thrown at 0x00007FF79D763488 in Sorting Algorithm Benchmarking Program.exe: 0xC0000005: Access violation writing location 0x000000BFBF600000. occurred

and

Unhandled exception at 0x00007FF79D763488 in Sorting Algorithm Benchmarking Program.exe: 0xC00000FD: Stack overflow (parameters: 0x0000000000000001, 0x00000058CE0B3000). occurred

I expected the sorted matrix to be printed in the console.

For example, if the unsorted matrix is:
1 9 5
8 3 6
7 4 2

then the output should be:
1 2 3
4 5 6
7 8 9

I would request you not to send complicated template-based suggestions, as I am in the intermediate level of C++ programming.

Thanks in advance!

c++
visual-studio
c++17
asked on Stack Overflow Sep 29, 2019 by Mithun K • edited Sep 29, 2019 by Mithun K

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0