c ++删除指针问题,仍然可以访问数据 [英] c++ delete pointer issue, can still access data

查看:237
本文介绍了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.

这篇关于c ++删除指针问题,仍然可以访问数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆