Segmentation fault when calling class from matlab

2019-08-06 19:23发布

I am getting a segmentation fault with the following code, and I really dont know what is happening here. It seems that it has something to do with the pointer in the Master-class, but I am not sure how to solve this. I have the following code:

class Shape
{
public:
    Shape(){}
    ~Shape(){}

    virtual void draw() = 0;
};

class Circle : public Shape
{
public:
    Circle(){}
    ~Circle(){}

    void draw()
    {
        printf("circle");
        // code for drawing circle
    }
};

class Line : public Shape
{
public:
    Line() {}
    ~Line() {}

    void draw()
    {
        printf("line");
        // code for drawing line
    }
};

class Master
{
public:
    Shape* member_shape;

public:
    Master()
    {}
    ~Master()
    {}

    void add_shape_circle()
    {
        member_shape = new Circle();
    }

    void add_shape_line()
    {
        member_shape = new Line();
    }
};

Master* master_object;

Do you have any clue how to get this code working? Thanks.

EDIT (added main function):

Actually there exists no main-function like the following in my code, because I am using the code in a MATLAB c-mex function. But it should look like this:

//... classes from above here
int main()
{
    master_object = new Master();
    master_object->add_shape_circle();
    master_object->member_shape->draw(); // segmentation error here

    return 0;
}
  1. EDIT

The error does not occur if I instatiate the Circle object dircetly in the Master-constructor. But then there is no way to choose between Line and Circle. Example: If I change my Master class to the following, then the function call master_object->member_shape->draw() does not lead to an error.

class Master
{
public:
    Shape* member_shape;

public:
    Master()
    {
        member_shape = new Circle();
    }
    ~Master()
    {}

    void add_shape_circle(){}

    void add_shape_line(){}
};

So, there is something up with this uninitialized pointer...I think.

1条回答
可以哭但决不认输i
2楼-- · 2019-08-06 19:32

The issue might be related to your using printf. From https://www.mathworks.com/help/matlab/matlab_external/creating-c-mex-files.html?requestedDomain=www.mathworks.com :

Using cout or the C-language printf function does not work as expected in C++ MEX files. Use the mexPrintf function instead.

查看更多
登录 后发表回答