[英]The segmentation fault is resolved, but cannot figure out why
The header file contains: 头文件包含:
class WorkScene;
class Mesh;
class Director
{
private:
WorkScene *scene = nullptr; // owner
Mesh *selected_mesh = nullptr; // borrower
public:
Director(WorkScene *scene);
~Director();
const Mesh *get_selected_mesh() const;
Mesh *get_selected_mesh();
};
The implementation of the get_selected_mesh
method is: get_selected_mesh
方法的实现是:
cvas::p3de::Mesh *cvas::p3de::Director::get_selected_mesh()
{
return selected_mesh;
}
However I receive a segmentation fault at this line: 但是我在这一行收到分段错误:
The segmentation fault error text is: 分段错误错误文本为:
The inferior stopped because it received a signal from the operating system.
下等停止,因为它从操作系统接收到信号。
Signal name : SIGSEGV
信号名称:SIGSEGV
Signal meaning : Segmentation fault
信号含义:分段故障
The segmentation fault is resolved when modifying the code like this: 修改如下代码时, 可以解决分段错误:
cvas::p3de::Mesh *cvas::p3de::Director::get_selected_mesh()
{
//return selected_mesh;
return nullptr;
}
Well, I can't figure out why the segmentation fault is resolved when modifying the code like above, considering the fact that inside the header file, the selected_mesh
identifier was already declared/initialized as nullptr
. 好吧,考虑到在头文件中
selected_mesh
标识符已经被声明/初始化为nullptr
的事实,我无法弄清楚为什么在修改上述代码时解决了分段错误。 Can anyone give me a hint? 谁能给我一个提示?
You seem to have a Director*
that is nullptr
and then you call get_selected_mesh
on that pointer. 您似乎有一个为
nullptr
的Director*
,然后在该指针上调用get_selected_mesh
。 This is undefined behavior. 这是未定义的行为。
In the case where you just return nullptr
the compiler does not care and just returns nullptr
. 在只
return nullptr
的情况下,编译器不在乎,而仅返回nullptr
。 In the case where you return selected_mesh
the compiler de facto needs to do a return this->selected_mesh
. 在
return selected_mesh
的情况下,编译器实际上需要return this->selected_mesh
。 This dereferences the invalid this
and thus the access violation. 这将取消引用无效的
this
,从而取消访问冲突。
The error is somewhere in the code that you do not show. 错误出现在您未显示的代码中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.