Unhandled exception at 0x00007FF982801B5F (ntdll.dll) in ConsoleApplication3.exe: 0xC0000005: Access violation reading location 0xFFFFFFFFFFFFFFFF

-3

I get this error "Unhandled exception at 0x00007FF982801B5F (ntdll.dll) in ConsoleApplication3.exe: 0xC0000005: Access violation reading location 0xFFFFFFFFFFFFFFFF" while trying to initialize a dynamic 2D array inside a class.

Here is my class

    class Board {
private:
    int boardSize;
    char** board = new char*[boardSize];
public:
    Board() {
        for (int i = 0; i < this->boardSize; i++) {
            this->board[i] = new char[this->boardSize];
        }
        for (int i = 0; i < this->boardSize; i++) {
            for (int j = 0; j < this->boardSize; j++) {
                this->board[i][j] = '-';
            }
        }
    }
    /*Board(int boardSize) {
        this->boardSize = boardSize;
        for (int i = 0; i < this->boardSize; i++) {
            this->board[i] = new char[this->boardSize];
        }
        for (int i = 0; i < this->boardSize; i++) {
            for (int j = 0; j < this->boardSize; j++) {
                this->board[i][j] = '-';
            }
        }
    } */
    Board(int boardSize, int c1r, int c1c, int c2r, int c2c) {
        this->boardSize = boardSize;
        for (int i = 0; i < this->boardSize; i++) {
            board[i] = new char[this->boardSize];
        }
        for (int i = 0; i < this->boardSize; i++) {
            for (int j = 0; j < this->boardSize; j++) {
                board[i][j] = '-';
            }
        }
        this->board[c1r][c1c] = 'C';
        this->board[c2r][c2c] = 'C';
        this->board[boardSize / 2][boardSize] = 'B';
    } 
    ~Board() {
        for (int i = 0; i < this->boardSize; i++) {
            delete[] this->board[i];
        }
        delete[] this->board;
    }
    void print_board() {
        for (int i = 0; i < this->boardSize; i++) {
            for (int j = 0; j < this->boardSize; j++) {
                std::cout << board[i][j] << "|";
            }
            std::cout << "\n";
        }
    }
};

and this is my main function

int main() {
    Animals duck;
    duck.move('d');
    std::cout << duck.getColumn() << "\n";
    Board playing_board(12, 2,2,4,4);
    playing_board.print_board();
}

Thank you

c++
asked on Stack Overflow Sep 13, 2020 by Mohamed A. Soliman • edited Sep 13, 2020 by Mohamed A. Soliman

1 Answer

0
char** board = new char*[boardSize];

The line above is setting you array to the size of what ever boardSize is initialized by the compiler (most likely 0). It doesn't get set it in the constructor. If you can use a debugger and see what it is set to in the board constructor.

If you want a dynamic 2D array you need to use something like

std::vector<std::string> board;

Or, move the new char*[boardSize] into the constructor so that you have the passed in value of boardSize.

answered on Stack Overflow Sep 13, 2020 by Nick M.

User contributions licensed under CC BY-SA 3.0