-2

I was trying some code. Mistakenly wrote below code (Luckily Now)

Snippet 1

#include<iostream>
using namespace std;

class A {
public:
    A() { cout << "A()" << endl; }
    ~A() { cout << "~A()" << endl; }
    void print() { cout << "A::print()=>" <<this<< endl; }
};

int main() {
    A* a = new A;
    a->print();
    delete a;
    a = NULL;
    cout << a << endl;  
    a->print();
    return 0;
}

As I know, since I have deleted "a", the program should have crashed (Not so true now). But it did not. Can some please explain the reason behind this. The output image is also attached.

But As soon as I include any member variable in the above program, it crashes. How ? Why ? Please see Program 2.

Snippet 2

class A {
int val;
public:
    A() { cout << "A()" << endl; }
    ~A() { cout << "~A()" << endl; }
    void print() { cout << "A::print()=>" <<this << val << endl; }
};

int main() {
    A* a = new A;
    a->print();
    delete a;
    a = NULL;
    cout << a << endl;  
    a->print();
    return 0;
}

The Above program is crashing. Why not the 1st program?

PS: There are chances that it may be the duplicate question. I tried to find the question like this but couldn't find. Though I got this question, I feel it's not the same as I am looking for.

enter image description here

A J
  • 720
  • 1
  • 8
  • 11
  • 1
    Undefined behavior is undefined. – melpomene Jul 28 '18 at 19:26
  • You're invoking undefined behavior. It's ill-formed to invoke functions on a null pointer to an object, but there's no guarantee of any kind as to what your program will do, since it's undefined. If you're lucky, you'll see a crash. If you're unlucky, your program will appear to work, only to give you the worst-behaved bugs in the future – alter_igel Jul 28 '18 at 19:26
  • @alterigel - You're mixing terms, and getting it wrong. Calling functions on a null pointer is not ill-formed. "Ill-formed" means that a diagnostic is required, which is not the case here. The behaviour here is "undefined", which means that the standard places no restrictions on behaviour of the program. – Peter Jul 29 '18 at 01:38

1 Answers1

1

The first one doesn’t dereference any memory pointed by anything, therefore it might not crash. You’re only printing out this which is a pointer value and you’re not dereferencing it. Note that this doesn’t mean it’s ok and will always work! It is definitely not allowed and shouldn’t be done. What happens when this is done is undefined.

Your second example actually tries to use a member variable which means an attempt is made to access memory that isn’t valid. This is also undefined behavior and may cause a crash, or something else. It is undefined.

Sami Kuhmonen
  • 30,146
  • 9
  • 61
  • 74