Search code examples
c++pointersmemoryconstructorcorrupt

Memory Corruption in C++ program


I'm trying to improve my C++ by writing a game of Conway's life.

The GameBoard object is getting corrupted. I call its print() method directly from the Game object constructor and it works. I then call it indirectly via from Game's print_board method and get an error on an integrity check.

Also, in main, there is a declaration of a variable I never use, but if I remove it, the error goes away. Somehow, I'm doing something to corrupt memory. It's probably pretty obvious.

Any assistance is greatly appreciated!

#include <iostream>
using namespace std;


class Board {
    int size;
    int grid[100][100];

    public:
        Board(int board_size) {size = board_size;}

        void print() {
            cout << "Board::print()" << endl;
            if (size < 1) {cout << "print: size must be > 0: size=" << size << "\n";  exit(1);}
        }
};

class GameRuleSet { }; // Methods removed

class Game {
  private:
    Board * game_board;
    GameRuleSet * rule_set;

  public:
     Game (GameRuleSet * p_rule_set, int p_board_size) {

        Board * game_board = new Board(p_board_size);

        cout << "Second Call - indirect..." << endl;
        game_board->print(); 

        cout << "Second Call - direct..." << endl;
        this->print_board(); // Error manifests from here
    }

    void print_board() {game_board->print();}
};


int main () {
    int num_turns = 10; // This line manifests error.
    int board_size = 10;

    GameRuleSet rule_set = GameRuleSet();
    Game game = Game(&rule_set, board_size);
}

Solution

  • You are re-declaring "Board* game_board" in your constructor which shadows the member variable of the same name. It then uses that allocated local game_board in the constructor to print.

    In the print_board() function it uses the unallocated member and therefore throws the error.

    Change the allocation from

    Board * game_board = new Board(p_board_size);
    

    to

    game_board = new Board(p_board_size);
    

    in the constructor to fix this.