Valgrind 数组在对象内溢出

leo*_*ong 4 c++ valgrind overrun

我有一个简单的程序,如下所示。

struct Test
{
    int a[5];
    int b;
};

int main()
{
    Test* t = new Test;
    t->b = 1;
    t->a[5] = 5;          //This is an illegal write
    cout << t->b << endl; //Output is 5
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

使用 Valgrind Memcheck 运行它没有报告非法内存写入。

我注意到 Valgrind 声称 Memcheck 工具无法检测全局或堆栈数组溢出,但这个数组在堆中,对吗?只是数组在一个对象中。

是 Valgrind 真的无法检测到这种错误还是只是我做错了什么?如果前者是真的,那么有没有其他工具可以检测这种类型的错误?

================================================== ========================

更新:

我使用的编译命令是g++ -O0 -g main.cc. 该valgrind命令很简单valgrind ./a.outmemcheck默认情况下应该调用该工具。

编译器版本是gcc version 4.4.7 20120313 (Red Hat 4.4.7-4) (GCC)valgrind版本是valgrind-3.5.0

运行此程序时的 Valgrind 输出:

==7759== Memcheck, a memory error detector
==7759== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.
==7759== Using Valgrind-3.5.0 and LibVEX; rerun with -h for copyright info
==7759== Command: ./a.out
==7759== 
5
==7759== 
==7759== HEAP SUMMARY:
==7759==     in use at exit: 24 bytes in 1 blocks
==7759==   total heap usage: 1 allocs, 0 frees, 24 bytes allocated
==7759== 
==7759== LEAK SUMMARY:
==7759==    definitely lost: 24 bytes in 1 blocks
==7759==    indirectly lost: 0 bytes in 0 blocks
==7759==      possibly lost: 0 bytes in 0 blocks
==7759==    still reachable: 0 bytes in 0 blocks
==7759==         suppressed: 0 bytes in 0 blocks
==7759== Rerun with --leak-check=full to see details of leaked memory
==7759== 
==7759== For counts of detected and suppressed errors, rerun with: -v
==7759== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 4 from 4)
Run Code Online (Sandbox Code Playgroud)

doq*_*tor 5

我认为下面的句子,你已经找到了:

Memcheck 无法检测您的程序存在的每个内存错误。例如,它无法检测对静态分配或堆栈上的数组的超出范围的读取或写入。但它应该检测到许多可能导致程序崩溃的错误(例如,导致分段错误)。

如果您的类定义应该这样解释: 虽然类对象是动态分配的,但数组本身是静态分配的

我已经验证了几个案例:

如果数组是动态分配的,Valgrind 将报告无效写入:

struct Test
{
    int *a;
    int b;
};

int main()
{
    Test* t = new Test;
    t->a = new int[5];
    t->b = 1;
    t->a[5] = 5;          //This is an illegal write
    cout << t->b << endl; //Output is 5
    delete [] t->a;
    delete t;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

如果将成员的顺序更改为:

struct Test
{
  int b;  
  int a[5];
};
Run Code Online (Sandbox Code Playgroud)

这是因为在尝试写入 a[5] 时,我们已经落后于动态分配的对象。

如果您尝试写入 a[6] ,则使用原始类定义 - 因为我们落后b于动态分配的对象。


更新:gcc sanitizer(我也怀疑clang)通过编译在运行时检测到这个越界访问:

g++ -fno-omit-frame-pointer -fsanitize=bounds m.cpp
Run Code Online (Sandbox Code Playgroud)

输出:

m.cpp:15:7: runtime error: index 5 out of bounds for type 'int [5]'
Run Code Online (Sandbox Code Playgroud)