c++pointersstack-corruption

Error "Stack around the variable was corrupted" in array of pointer C++


I have a class Piece and class Board, which represent chess pieces and board. In the Board class, I have an array of 8*8 pointers of type Piece, which I expect to hold pointers from index 0 to 63.

However, I get an error in the code below:

Stack around the variable 'chess_board' was corrupted

Piece* m_Board[8 * 8];

Board() {
    int i = 0;
    //Black pawns
    std::cout << i << std::endl;
    m_Board[i] = new Rook(i++, 1);
    m_Board[i] = new Knight(i++, 1);
    m_Board[i] = new Bishop(i++, 1);
    m_Board[i] = new Queen(i++, 1);
    m_Board[i] = new King(i++, 1);
    m_Board[i] = new Bishop(i++, 1);
    m_Board[i] = new Knight(i++, 1);
    m_Board[i] = new Rook(i++, 1);
    //Black pieces
    for (i; i < 16; i++) {
        m_Board[i] = new Pawn(i, 1);
    }
    //Blank squares
    std::cout << i << std::endl;
    for (i; i < 48; i++) {
        m_Board[i] = nullptr;
    }
    //White pawns
    for (i; i < 56; i++) {
        m_Board[i] = new Pawn(i, 0);
    }
    //White pieces
    m_Board[i] = new Rook(i++, 0);
    m_Board[i] = new Knight(i++, 0);
    m_Board[i] = new Bishop(i++, 0);
    m_Board[i] = new Queen(i++, 0);
    m_Board[i] = new King(i++, 0);
    m_Board[i] = new Bishop(i++, 0);
    m_Board[i] = new Knight(i++, 0);
    m_Board[i] = new Rook(i++, 0);
}

After some testing, I found that the error occurs at the last m_Board[i] = new Rook(i++, 0); line, where variable i goes from 63 to 64. If I change that line to m_Board[i] = new Rook(i, 0);, the error disappears.

I wonder what effect i++ has, as I thought that m_Board[i] = new Rook(i++, 0); is similar to m_Board[i] = new Rook(i, 0); i++?

I only access to the 63th element of the array, and pass variable i to the constructor of a Rook object, after that variable i will increment by 1.

How does that generate an error?


Solution

  • m_Board[i] = new Rook(i++, 0); and m_Board[i] = new Rook(i, 0); i++; is not the same. These are two different sequence point.

    To quote cpp reference

    A sequence point is a point in the execution sequence where all side effects from the previous evaluations in the sequence are complete, and no side effects of the subsequent evaluations started.

    Also

    There is a sequence point at the end of each full expression (typically, at the semicolon).

    a[i] = i++; // undefined behavior (until C++17)
    

    Kindly have a look at the following articles: