简体   繁体   中英

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:

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

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 . 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. This is undefined behavior.

In the case where you just return nullptr the compiler does not care and just returns nullptr . In the case where you return selected_mesh the compiler de facto needs to do a return this->selected_mesh . This dereferences the invalid this and thus the access violation.

The error is somewhere in the code that you do not show.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM