c++删除指针问题,仍然可以访问数据

2021-12-13 00:00:00 pointers c++

我真的不明白为什么这些指针可以访问......感谢任何帮助

I don't really understand why are those pointer accessible ... any help appreciated

#include <iostream>

class Wicked{
public:
    Wicked() {};
    virtual ~Wicked() {};

    int a;
    int b;
};


class Test
{
public:
    Test() {};
    virtual ~Test() {};

    int c;

    Wicked * TestFunc()
    {
        Wicked * z;
        c = 9;
        z = new Wicked;
        z->a = 1;
        z->b = 5;
        return z;
    };
};

int main()
{
    Wicked *z;

    Test *t = new Test();
    z = t->TestFunc();

    delete z;
    delete t;

    // why can I set 'z' when pointer is already destroyed?
    z->a = 10;

    // why does z->a print 10?
    std::cout << z->a << std::endl;

    // why does t->c exist and print correct value?
    std::cout << t->c << std::endl;

    //------------------------------------------------------

    int * p = new int;
    *p = 4;

    // this prints '4' as expected
    std::cout << *p << std::endl;

    delete p;

    // this prints memory address as expected
    std::cout << *p << std::endl;

    return 0;
}

推荐答案

删除指针不会将任何内存清零,因为这样做会占用 CPU 周期,而这不是 C++ 的意义所在.您所拥有的是一个悬空指针,并且可能是一个微妙的错误.像这样的代码有时可以工作多年,但在未来的某个时候,当程序中的其他地方进行了一些小的更改时,它就会崩溃.

Deleting a pointer doesn't zero out any memory because to do so would take CPU cycles and that's not what C++ is about. What you have there is a dangling pointer, and potentially a subtle error. Code like this can sometimes work for years only to crash at some point in the future when some minor change is made somewhere else in the program.

这是当您删除指针指向的内存时应该将指针设为 NULL 的一个很好的理由,这样如果您尝试取消引用指针,您将立即收到错误消息.有时使用 memset() 之类的函数清除指向的内存也是一个好主意.如果指向的内存包含机密信息(例如明文密码),您不希望程序的其他部分(可能面向用户)访问这些部分,则尤其如此.

This is a good reason why you should NULL out pointers when you've deleted the memory they point to, that way you'll get an immediate error if you try to dereference the pointer. It's also sometimes a good idea to clear the memory pointed to using a function like memset(). This is particularly true if the memory pointed to contains something confidential (e.g. a plaintext password) which you don't want other, possibly user facing, parts of your program from having access to.

相关文章