且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-12 22:31:04

删除指针零任何内存,因为这样做将需要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.