問題描述
我真的不明白為什么這些指針可以訪問......感謝任何幫助
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++刪除指針問題,仍然可以訪問數據的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!