c++loopssudoku

C++ Run-Time Check Failure #2 Error in Sudoku Generator


i wrote a code which has loops for creating sudoku table after each problem loop starts again and that causes for so much tries it works fine but at the end i got an error

int TableGenerator() {
    int Table[9][9] = {
        {0, 0, 0, 0, 0, 0, 0, 0, 0},
        {0, 0, 0, 0, 0, 0, 0, 0, 0},
        {0, 0, 0, 0, 0, 0, 0, 0, 0},
        {0, 0, 0, 0, 0, 0, 0, 0, 0},
        {0, 0, 0, 0, 0, 0, 0, 0, 0},
        {0, 0, 0, 0, 0, 0, 0, 0, 0},
        {0, 0, 0, 0, 0, 0, 0, 0, 0},
        {0, 0, 0, 0, 0, 0, 0, 0, 0},
        {0, 0, 0, 0, 0, 0, 0, 0, 0},
    };

    srand(time(nullptr));
    list<int> AvailableNumbers;

    int ySquare;
    int xSquare;

    int y = 0;
    int x;

    while (y < 9) {
        AvailableNumbers = { 1,2,3,4,5,6,7,8,9 };
        x = 0;
        while (x < 9) {
            list<int> ColumnAvailableNumbers = AvailableNumbers;
            ySquare = y - (y % 3);
            xSquare = x - (x % 3);
            for (int yCoSquare = ySquare; yCoSquare < ySquare + 3; yCoSquare++) {
                for (int xCoSquare = xSquare; xCoSquare < xSquare + 3; xCoSquare++) {
                    ColumnAvailableNumbers.remove(Table[yCoSquare][xCoSquare]);
                }
            }
            for (int Checker = 0; Checker < y; Checker++) {
                ColumnAvailableNumbers.remove(Table[Checker][x]);
            }

            if (ColumnAvailableNumbers.size() > 0) {
                auto it = next(ColumnAvailableNumbers.begin(), rand() % ColumnAvailableNumbers.size());
                Table[y][x] = *it;
                AvailableNumbers.remove(*it);
            }
            else {
                for (int yClear = 0; yClear < 9; yClear++) {
                    for (int xClear = 0; xClear < 9; xClear++) {
                        Table[yClear][xClear] = 0;
                    }
                }
                y = -1;
            }

            x++;
        }
        y++;
    }

    for (int y = 0; y < 9; y++) {
        for (int x = 0; x < 9; x++) {
            std::cout << Table[y][x];
        }
        cout << endl;
    }
    return 0;
}

this is the error:

Debug Error! Program: E:\Sudoku.exe Module: E:\Sudoku.exe File:

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

(Press Retry to debug the application)


Solution

  • Since you set y = -1; then Table[y][x] = *it; will have undefined behavior in the next iteration.

    If you want the outer loop to continue iterating, just break out of the inner loop after setting y = -1.

    y = -1;
    break;
    

    If you want to end both loops, you could instead set it to 9 and break out of the inner loop.

    y = 9;
    break;