Search code examples
c++pointerswhile-loopbase-classabstract-base-class

Pointer to base class lost in while loop, causing segfault. C++


This code uses a while loop to get user input and execute the appropriate command - I've reduced it to 2 commands for sake of brevity.
The Oblock object is created correctly (command "O"), as is the pointer to the base class. It appears that the calls to both objects work correctly as well. However, after returning to the while loop, the pointer to the object appears to be lost, and attempting to access its members (command "t") causes a segfault. I've included the example code below - my questions are afterwards.

#include<vector>
#include<iostream>
#include<string.h>

using namespace std;

class Tetramino {
    private:
        int squareSize;
        vector<string> myShape;
    public:
        void setValues(int size) {
            squareSize = size;
            myShape = vector<string> ((size*size), ".");
        }
        string getValues(int i) {
            return myShape[i];
        }
        int getSize() {
            return squareSize;
        }
};

class Oblock : public Tetramino {
    public:
    Oblock() {
        setValues(2);
    }
};

main () {
    string input;
    bool runProgram = true;
    Tetramino *pBlock;

    while (runProgram) {
        cin >> input;
        if (input == "O")
            {
                Oblock myBlock;
                cerr << "0thi: " << myBlock.getValues(0) << endl;
                Tetramino *pBlock = &myBlock;
                cerr << "0thi: " << pBlock->getValues(0) << endl;
            }
        if (input == "t")
            {
                cerr << "0thi: " << pBlock->getValues(0) << endl;
            }
        }
    return 0;
}
  • Are objects deconstructed upon exiting the if statements?
  • Is there perhaps a better way to repeatedly get user input?

Thanks in advance for any advice! I searched for questions similar to this one and couldn't find one appropriate for my needs.


Solution

  • Tetramino *pBlock is local within its scope. You're shadowing over the one in main with the one within the if.

    Also, myBlock is local and will be destructed - you'll have a dangling pointer. You should allocate with new (and delete...)

    Instead of Tetramino *pBlock = &myBlock; do pBlock = new Oblock; when you handle the "O" input (and handle delete pBlock of the previous one).