简体   繁体   中英

Why does it NOT seg fault on dereference? unique_ptr

I would expect the following code to segmentation fault before it gets inside the method and print anything. Why doesn't it? How come the execution can go inside the method and print output for example?

#include <memory>
#include <vector>
#include <iostream>

class Foo{
    public:
        void method(int x){
            std::cout << "wut" << std::endl;
            m_list.push_back(x);
        }
    private:
        std::vector<int> m_list;
};

int main()
{
    std::unique_ptr<Foo> example;
    example->method(0);
}

This is, of course, undefined behavior, as others have pointed out.

However, in many C++ implementations, this will indeed not crash until after the output, because the NULL pointer is never actually dereferenced before then.

Your main essentially boils down to reinterpret_cast<Foo *>(nullptr)->method(0) . Since method is a non- virtual method of class Foo , that translates to Foo::method(0) (with this set to nullptr ).

The output line does not reference this at all, so it's only when m_list is accessed that this is first dereferenced (and consequently crashes).

If method had been virtual , the call to it most likely would have crashed, as in typical implementations, calls to virtual methods do dereference this .

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