我有一个简单的程序如下。
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;
}
用 Valgrind Memcheck 运行它并没有报告非法内存写入。
我注意到 Valgrind 声称 Memcheck 工具无法检测到全局或堆栈数组溢出,但这个数组在堆中,对吧?只是数组在一个对象中。
是 Valgrind 真的无法检测到这种错误还是我做错了什么?如果前者是真的,那么有没有其他工具可以检测到这种类型的错误?
==================================================== =========================
更新:
我使用的编译命令是g++ -O0 -g main.cc
. 该valgrind
命令很简单valgrind ./a.out
,默认情况下应该调用该memcheck
工具。
编译器版本是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)