Search code examples
c++fsm

Simple program crash


I tried to implement a very simple FSM in C++. Problem is, that this program will crash immediately, after executing. I am new to C++ so I can't find any bug here. Can anyone help? Thanks in advance!

#include <iostream>
using namespace std;

class State {
    public:
        virtual ~State() {}
        virtual void update();
};

class Hey_state : public State {
    public:
        virtual void update() { cout << "Hey!\n";}
};

class How_state : public State {
    public:
        virtual void update() { cout << "How are you?\n";}
};

class Stranger {
    public:
        Stranger(State *startState)
        : currState(startState) {}
        void greet() {
            currState->update();
        }
        void setState(State *s) {currState = s;}
    private:
        State *currState;
};

int main() {
    Hey_state *h;
    Stranger s(h);
    s.greet();
}

Solution

  • Hey_state *h;

    This creates a pointer to a Hey_state which could point anywhere randomly in memory. No object is actually created.

    Stranger s(h);
    s.greet();
    

    This attempts to use the Hey_state that was never created, giving an error.

    Try:

    Hey_state h;
    Stranger s(&h);
    s.greet();
    

    That creates an object of Hey_state, and passes a pointer to that object to Stranger s