问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/35877487/dangling-pointer-is-still-accessing-the-memory-value