dangling pointer is still accessing the memory value [duplicate]

試著忘記壹切 提交于 2019-12-13 23:57:35

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!