在基类指针上调用方法时出现分段错误
我正在尝试为简单的编译器构建 FSM。
我选择创建一个固定大小的数组,其中包含指向状态的接口指针。事实证明,这个概念通过读取 HTML 的简单占位符 FSM 是成功的。
然而,真正的 FSM 不起作用:调用状态处理方法时出现分段错误(位于 0x0)。
这是实例:
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();
[...]
当我单步执行它时,我可以看到每次分配后相应的地址都会发生变化。
该数组的定义方式如下:
#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,出于测试目的而最小化代码:
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;
};
现在,以下代码行导致 SEGFAULT:
this->nextState = this->states[currentState]->getNextState(c);
currentState
为 0,因为它发生在第一次调用时。
所以,我认为这既不是范围问题,也不是 NULL 指针。除了状态对象中的 NULL this 指针?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如评论中提到的,这个问题是由于我自己的粗心造成的。我编辑了 Makefile 来构建其他对象,但未能将代码中的标头更改为新标头。因此,我将(“外部”类似)新目标文件链接到仍使用旧标头的其他代码。
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.