3

Let's consider this piece of code:

struct config
{
    int get( )
    {
        if ( this == nullptr ) return 1;
        return value;
    }

    int value = 5;
};

config* c = nullptr;
int result = c->get();

This works both in clang and gcc (I think in MSVC too). Is this (running a function on a nullptr pointer) undefined behaviour? If so (or not) where in the C++ standard is this defined as UB or allowed?

Kornel Kisielewicz
  • 55,802
  • 15
  • 111
  • 149
  • Dereferencing a null pointer is undefined, even if it's only "conceptual" (i.e. no actual memory access occurs). As far as I can tell, this is only mentioned in a note (section 11.3.2 in C++17): "[...] indirection through a null pointer, which causes undefined behavior." – molbdnilo Feb 20 '18 at 10:26
  • @molbdnilo is it ub to call method via pointer , if method does not dereferences this. (call method which is essentualy static, but not declared as one) . I thought in this case pointer via which method is called is just unused parameter and it is irrelevant whether pointer points to valid object or not. – Andrew Kashpur Feb 20 '18 at 10:39
  • 1
    @AndrewKashpur You can't call a member function on a pointer without dereferencing it - both `*` and `->` dereference the pointer. (Dereferencing does not necessarily involve any memory access, but can be undefined nonetheless.) Dereferencing a null pointer is undefined even if you're calling a static member function; if `get` were static, `c->get()` would be undefined but `config::get()` would be fine. – molbdnilo Feb 20 '18 at 11:58
  • Where this comes into play is that the compiler's optimizer can rely on this being the case, so can treat the "impossible" code as a "never can happen" code path and cull it out. – Eljay Feb 20 '18 at 13:27

0 Answers0