什么会导致删除在我的类的数据字段中留下垃圾值?
我有一个节点类,其中包含 3 个节点指针和 2 个整数。我使用 new
分配所有节点,但是当我对它们调用 delete
时,整数被设置为 -17891602
并且它搞砸了其余的我的代码的边界检查。什么会导致 delete
这样做?
I have a node class that contains 3 node pointers and 2 integers. I allocate all the nodes with new
, but when I call delete
on them, the integers get set to -17891602
and it's screwing up the rest of my code's boundary checking. What would cause delete
to do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
删除
之后,该内存就不再属于您了。不要检查它,不要用它做任何事情,因为如果你这样做,那么你就有了未定义的行为。它可能很快就会被重复使用。After a
delete
that memory is not yours any more. Don't inspect it, don't do anything with it, because if you do then you have Undefined Behavior. It will likely soon be reused.检查指针字段是否也获得新值。它们等于 0xfeeefeee 吗? (十六进制为 -17891602。)您的内存管理器可能会覆盖已释放的内存,因此当您尝试读取或写入不应该再访问的内存时,可以更容易地在故障转储中识别。
如果您正在读取释放的对象来进行边界检查,那么您就依赖于未定义的行为。检查您的环境的文档,了解它对释放的内存做了什么(如果有的话)。您的边界检查器需要与其合作;你不能假设它在一般情况下都能工作。
Check whether the pointer fields also get new values. Are they equal to 0xfeeefeee? (That's -17891602 in hexadecimal.) Your memory manager might be overwriting freed memory so it's easier to recognize in crash dumps when you attempt to read or write memory you're not supposed to access anymore.
If you're reading freed objects to do bounds checking, then you're relying on undefined behavior. Check the documentation for your environment to find out what, if anything, it does with freed memory. Your bounds checker will need to co-operate with it; you cannot assume it will work in the general case.
如果您在 Linux 上进行开发并使用
gdb
,您可以使用watch
命令将观察点添加到 GDB。这可以帮助查找内存位置何时被覆盖。If you develop on Linux and use
gdb
you could put a watchpoint using thewatch
command to GDB. This can help finding when was a memory location overwritten.