0

I would expect the following code to crash at runtime with a null pointer error:

#include <memory>
#include <iostream>
#include <cassert>

struct Foo {
    void echo() {std::cout << "Echo" << std::endl;}
};

int main()
{
    std::unique_ptr<Foo> up(new Foo());
    up.reset(nullptr);

    assert(up.get() == nullptr);

    up.get()->echo();
}

however both gcc (4.7/4.8/4.9), msvc (2013 and upcoming 2015) and clang (3.5) happily outputs:

Echo

and assert is not firing so up.get() is nullptr.

ismail
  • 46,010
  • 9
  • 86
  • 95

2 Answers2

2

You are essentially calling a member function with an invalid object argument - which is generally considered to trigger undefined behavior. However, you are not using this inside the member funtion, so no Segfaults should occur practically.

Try adding a member and accessing that member inside echo. That should crash your program. I.e.

struct Foo
{
    int i;
    void echo() {std::cout << i << std::endl;}
};
Columbo
  • 60,038
  • 8
  • 155
  • 203
  • The error is earlier, see the duplicate. – Deduplicator Nov 23 '14 at 16:02
  • @Deduplicator What do you mean? Dereferencing a null pointer? dyp says otherwise. I've used the same argumentation myself some time ago. – Columbo Nov 23 '14 at 16:06
  • @Columbo: Dyp says dereferencing a null-pointer *in C++* is fine? Where, and what are his arguments? I hope it's not "it seems to work". Because I would be *very* interested in anything allowing dereferencing null-pointers, especially as it breaks the guarantee that references always represent an object. – Deduplicator Nov 23 '14 at 16:10
  • Dereferencing a null-pointer yields an lvalue. No reference is created per se. I'll find the comment where we had the discussion. – Columbo Nov 23 '14 at 16:13
  • @Deduplicator I mixed it up a little bit. [**Here**](http://stackoverflow.com/questions/26168164/lambda-expressions-as-class-template-parameters-in-c14#comment41046731_26170459) are the comments. Also consider hvd's last comment. – Columbo Nov 23 '14 at 16:19
0

Calling member function through NULL pointer is surely an undefined behavior.

Your call to that member function is successful as you are not making use of this pointer.

ravi
  • 10,994
  • 1
  • 18
  • 36