简体   繁体   中英

get segfault when creating a pointer c++

I got a Segmentation fault error when I compile it on an online c++ compiler. (The line that throws the error will be pointed out by a comment in the code)

#include <iostream>
#include <memory>

class A
{

};

class B:public A
{

};


using namespace std;
class Base
{
public:
    int b;
    std::shared_ptr<A> Display()
    {
        cout<<"Base: Non-virtual display."<<endl;
    };
    virtual void vDisplay()
    {
        cout<<"Base: Virtual display."<<endl;
    };
};

class Derived : public Base
{
public:
    int d;
    std::shared_ptr<B> Display()
    {
        cout<<"Derived: Non-virtual display."<<endl;
    };
    virtual void vDisplay()
    {
        cout<<"Derived: Virtual display."<<endl;
    };
};

int main()
{
    cout<<"Hello World"<<endl;
    Derived d;
    d.Display();

    Base *b = new Derived; // this line thorws the error
    b->vDisplay();
    return 0;
}

I got a bit confused; if I just create an object instead of pointer, then it's good. Where did I make a mistake?

Error actually happens on the previous line d.Display(); . Control flow leaves Derived::Display() function without returning std::shared_ptr<B> causing Undefined Behavior.

As other people suggest, it would be a good idea to enable compiler warnings and / or actually pay attention to them. This is that one rare case when compilers tend to actually warn about potentially Undefined behavior in your program.

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