0

When I executed the code below,

#include <memory>
#include <iostream>

class AAA
{
    public:
        AAA(void)
        {
            std::cout<<"Ctor"<<std::endl;
        }

        void show()
        {
            std::cout<<"Foo"<<std::endl;
        }
};

int main(void)
{
    std::shared_ptr<AAA> a; // uninitialized

    a->show();

    return 0;
}

The result comes out like this without any failure:

Foo

But I guess shouldn't a seg fault or something occur at the time of calling a->show() ?

And when I checked further, if there was a member variable, then a seg fault occurred.

#include <memory>
#include <iostream>

class AAA
{
    public:
        AAA(void)
        {
            std::cout<<"Ctor"<<std::endl;
        }

        void show()
        {
            std::cout<<"Foo"<<std::endl;
            std::cout<<mData;
        }

    private:
        int mData;
};

int main(void)
{
    std::shared_ptr<AAA> a;

    a->show();

    return 0;
}

The result comes out like this:

Foo
Segmentation fault (core dumped)

What is the reason for these differences? In particular, I wonder why the seg fault did not occur in the first case.

user7024
  • 311
  • 2
  • 10
  • 2
    *"Undefined behavior means anything can happen including but not limited to the program giving your expected output. But never rely(or make conclusions based) on the output of a program that has UB. The program may just crash."* – Jason Jan 27 '23 at 03:23
  • You are working on UB. The non-virtual member function exists whether or not the object does. Calling it works whether or not the object does. Only when you try to access data that does not exit (the object or any data belonging to the object) do things go wrong. – Dúthomhas Jan 27 '23 at 03:29
  • https://en.cppreference.com/w/cpp/language/ub – Jesper Juhl Jan 27 '23 at 04:45
  • You are calling the member function with `this` being a null pointer. If the code happens to not use the pointer (like when the class has no members), it might not notice the error. – BoP Jan 27 '23 at 08:59
  • Another thing - `int main(void)` in C you have to say `void` to show that there are no parameters to the function. In C++ a set of empty parenthesis `()` already means that. The `void` is not needed. – BoP Jan 27 '23 at 09:04

0 Answers0