I’m trying to construct a FSM for a simple compiler.
I’ve chosen to create a fixed-size array with interface pointers to the states. This concept proved to be successful with a simple placeholder FSM that reads HTML.
However, the real FSM won’t work: I get a segmentation fault (at 0x0) when calling a states processing method.
Here’s the instancing:
this->states[0] = new State0();
this->states[1] = new State1();
this->states[2] = new State2();
this->states[3] = new State3();
this->states[4] = new State4();
[...]
When I step through it, I can see the corresponding address changing after each assignment.
The array is defined this way:
#define STATE_COUNT 17
[...]
IState * states[STATE_COUNT];
IState:
class IState {
public:
virtual ~IState() {};
virtual int getNextState(char) = 0;
virtual bool isFinal() = 0;
virtual TokenType getTokenType() = 0;
};
State0, with code minimized for testing purposes:
class State0 : public IState
{
public:
virtual ~State0();
int getNextState(char c)
{
return 0;
}
bool isFinal()
{
return this->final;
}
TokenType getTokenType()
{
return this->tokenType;
}
private:
TokenType tokenType;
bool final;
};
Now, the following line of code causes the SEGFAULT:
this->nextState = this->states[currentState]->getNextState(c);
currentState is 0, since it happends on the very first call.
So, I think it’s neither a scope problem nor a NULL pointer. Except perhaps a NULL this pointer in the state objects?
As mentioned in the comments, this problem was due to my own carelessness. I edited my Makefile to build other objects but failed to change the headers to the new ones in my code. So I linked (“externally” similar) new object files to other code still using the old headers.