c++ - Valgrind 未检测到危险的释放内存

标签 c++ debugging memory memory-management valgrind

我正在学习 valgrind 框架,我决定在我自己的小测试用例上运行它。这是以下程序,它强制从堆中删除额外的对象(我在 AMD64/LINUX 上运行它):

#include <iostream>
using namespace std;

struct Foo
{
    Foo(){ cout << "Creation Foo" << endl;}
    ~Foo(){ cout << "Deletion Foo" << endl;}
};

int main()
{
    Foo* ar = new Foo[3];
    *(reinterpret_cast<int*>(ar)-2) = 4;
    delete[] ar;
    return 0;
}

但是 valgrind 的执行结果让我很困惑:

$ valgrind --leak-check=full ./a.out -v

==17649== Memcheck, a memory error detector

==17649== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.

==17649== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info

==17649== Command: ./a.out -v

==17649==

Creation Foo

Creation Foo

Creation Foo

Deletion Foo

Deletion Foo

Deletion Foo

Deletion Foo

==17649==

==17649== HEAP SUMMARY:

==17649== in use at exit: 72,704 bytes in 1 blocks

==17649== total heap usage: 3 allocs, 2 frees, 73,739 bytes allocated

==17649==

==17649== LEAK SUMMARY:

==17649== definitely lost: 0 bytes in 0 blocks

==17649== indirectly lost: 0 bytes in 0 blocks

==17649== possibly lost: 0 bytes in 0 blocks

==17649== still reachable: 72,704 bytes in 1 blocks

==17649== suppressed: 0 bytes in 0 blocks

==17649== Reachable blocks (those to which a pointer was found) are not shown.

==17649== To see them, rerun with: --leak-check=full --show-leak-kinds=all

==17649==

==17649== For counts of detected and suppressed errors, rerun with: -v

==17649== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

似乎 valgrind(版本 3.13.0)没有检测到任何内存损坏?

UPD:我用g++ -g main.cpp命令编译了main.cpp

最佳答案

Valgrind 没有检测到数组“前缀”的变化,可能是因为它是内存的有效部分。即使它不应该被用户代码直接更改,它仍然可以被数组构造函数代码访问和修改,而 valgrind 不提供这种精细的访问检查分离。另请注意,此损坏似乎并未损坏堆,因此释放成功。

Valgrid 未检测到对无效对象的析构函数调用可能是因为此调用实际上并未访问无效存储。添加一些类字段将改变这种情况:

struct Foo
{
    int i;
    Foo(): i(0) { cout << i << "Creation Foo" << endl;}
   ~Foo(){ cout << i << "Deletion Foo" << endl;}
};

Invalid read of size 4

关于c++ - Valgrind 未检测到危险的释放内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48240736/

相关文章:

c - 从堆栈分配 - C 中的数据对齐问题

Java堆硬盘

python - 在长时间运行的进程中重新加载全局Python变量

C++ fseek : Is the first byte at position 0 or 1?

c++ - 在 Xcode 中为 OpenCV 组合两个 c++ 文件(使用未声明的标识符 CVSquares)

javascript - 尝试对 JavaScript 函数进行计时时出现错误

visual-studio - VS2005经常崩溃时编译

c++ - 如何在 Visual Studio 的 Windows 窗体 C++.NET 项目中添加 native C++ dll?

c++ - 当两个类共享同一个堆对象时,如何避免删除指针两次?

asp.net - VS 2013 ASP.NET调试时无法修改代码