Home > Mobile >  I keep getting this error and it is getting me more and more frustrated, please help me out
I keep getting this error and it is getting me more and more frustrated, please help me out

Time:10-08

Line 1034: Char 9: runtime error: reference binding to null pointer of type 'std::vector<int, std::allocator>' (stl_vector.h) SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c /9/bits/stl_vector.h:1043:9

void gameOfLife(vector<vector<int>>& board) {
   vector<vector<int>> newBoard;
    for(int i = 0; i < board.size(); i  ){
        for(int j = 0; j < board[i].size(); j  ){
            if(board[i][j] == 0 && neibSum(board,i,j) == 3)
                newBoard[i][j] = 1;
            else if(board[i][j] == 1 && neibSum(board,i,j) > 3)
                newBoard[i][j] = 0;
            else if(board[i][j] == 1 && neibSum(board,i,j) < 2)
                newBoard[i][j] = 0;
            else
                newBoard[i][j] = 1;
        }
    }
    for(int i = 0; i < board.size(); i  ){
        for(int j = 0; j < board[i].size(); j  ){
            cout << newBoard[i][j] << " ";
        }
        cout << endl;
    }
    
}

CodePudding user response:

Your variable 'newboard' is a vector of size 0. in:

newBoard[i][j] = 1;

you are trying to access unallocated memory. You need to allocate the memory first (using, e.g., resize).

   vector<vector<int>> newBoard;
    newBoard.resize(board.size());
    for(int i = 0; i < board.size(); i  ){
        newBoard[i].resize(board[i].size());
        for(int j = 0; j < board[i].size(); j  ){
...

edit: p.s., you can use the .at() function, instead of [] to access vector elements: newBoard.at(i).at(j) This contains bounds checking. It won't solve your problem, but it will give you a much easier-to-understand error message.

CodePudding user response:

You can initialize your board in one line

#include <vector>

// two constants for you board size
// stl containers mostly accept std::size_t for their sizes
constexpr std::size_t board_height_v = 25;
constexpr std::size_t board_width_v = 80;

enum class cell
{
    dead,
    alive
};

int main()
{
    // I made a cell enum so you can more easily spot where the initial cell value is set.
    // now lets initialize the board to the correct size
    std::vector<std::vector<cell>> newBoard(board_height_v, std::vector<cell>(board_width_v,cell::dead));

    return 1;
}
  • Related