gpt4 book ai didi

c++ - 如何检查将 free() 与 new [] 一起使用的后果

转载 作者:太空狗 更新时间:2023-10-29 20:06:32 25 4
gpt4 key购买 nike

进程因 SIGSEV 而崩溃,回溯表明内存损坏。Valgrind 报告表明存在一些“空闲不匹配”,即使用 new[] 分配的内存正在使用 free() 释放。

我找到了以下 information from cert.org

Another potential problem is that when passing a pointer to an array allocated with operator new to operator delete(), it is possible that when free() is called by operator delete() (as is common in many implementations, although not required by the C++ Standard), the pointer passed to free() is not one that was returned by a call to malloc(). This is because the first four bytes returned by malloc() when called by operator new will typically be used to store the size of the array (again, not specified by the Standard, but common), so the pointer returned by operator new actually points to an address that is four bytes from the pointer returned by malloc(). Consequently, free() will read in the wrong size to deallocate, and this could lead to heap memory corruption problems.

问题是,我怎样才能证明 free() 正在释放错误的大小?任何人都可以建议如何验证这是否发生在我的环境中,可能使用 gdb 或任何其他工具?

另外,数组是基本类型char,所以不存在不调用单独析构函数的问题。

最佳答案

Question is, how can I demonstrate that free() is deallocating wrong size?

Can anyone suggest how to verify that this is happening in my environment, maybe with gdb or any other tools?

您已经运行了一个工具,它告诉您这就是正在发生的事情。为什么您要运行另一个工具来验证“这确实是正在发生的事情”?

根据 Valgrind,您不匹配一些 free 调用。这就是问题,这就是您需要解决的问题。

只要该问题存在,它就可能产生一百万种不同的后果,其中之一就是您引用的文本中所描述的。但是您不需要知道程序中实际上发生了这百万种后果中的哪些,因为这些只是症状,您已经知道原因是什么 .

当您不匹配 free/delete 时,唯一保证的效果是“发生了一些事情”。那“东西”是什么?谁也说不准。

除非您是故意尝试编写糟糕的软件,否则您应该从源头上解决问题,而您的要求对您没有帮助。

关于c++ - 如何检查将 free() 与 new [] 一起使用的后果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7647964/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com