-2

I am pretty new to this concept and I am confused that if a dangling pointer is a pointer which points to a memory location which points to memory which has been freed or deleted then in this case why it is still able to call the function test()

#include <stdio.h>
#include <iostream>
#include <stdlib.h>
using namespace std;

class MyClass{

    public:
    void test(){

        cout<< "just checking"<<endl;

        }

    };

int main(int argc, char **argv)
{
    MyClass *p ( new MyClass());; 
    MyClass  *q = p;
    delete p;
    q->test();

    p = NULL;
    q->test();
    return 0;
}

Any help would be appreciated.

too honest for this site
  • 12,050
  • 4
  • 30
  • 52
StealthTrails
  • 2,281
  • 8
  • 43
  • 67
  • You are invoking [undefined behavior](https://en.wikipedia.org/wiki/Undefined_behavior). This means that the compiler is free to produce whatever code it wishes, including code that appears to work. – R_Kapp Mar 08 '16 at 20:37
  • 1
    and this question has absolutely nothing to do with C. – Sourav Ghosh Mar 08 '16 at 20:38
  • If you're on Windows it's easier to spot dangling pointers - in Debug mode Visual Studio fills freed memory with 0xCD bytes. – rustyx Mar 08 '16 at 20:47

1 Answers1

4

Delete runs the destructor of the class, and marks the memory as freed. If the destructor doesn't do anything too destructive, and if the memory has not yet been reallocated for some other purpose, then the object turns into what is basically a zombie: it looks vaguely like one of the living, but is really preparing to eat your brain.

Don't let your brain get eaten.

H. Guijt
  • 3,325
  • 11
  • 16