-1

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);
}
Celestia
  • 83
  • 1
  • 4
  • 2
    Undefined behavior is just that -- undefined. Anything can happen when your program causes undefined behavior -- including seemingly sane behavior. – R Sahu Jul 02 '19 at 04:30
  • 1
    Possible duplicate of [This code appears to achieve the return of a null reference in C++](https://stackoverflow.com/questions/2894891/this-code-appears-to-achieve-the-return-of-a-null-reference-in-c) – rsjaffe Jul 02 '19 at 04:31

1 Answers1

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.

microtherion
  • 3,938
  • 1
  • 15
  • 18
  • Thanks. I thought it required an instance to reference to get to get there but apparently not and it makes a bit more sense seeing your rephrasing of the call. It wasn't a shock to me that it seg faulted inside. I guess my c++ is rusty. I thought for sure the non-smart pointer would be different but it behaves in the same undefined way. – Celestia Jul 02 '19 at 04:51