valgrind 的一个小缺陷

valgrind 在项目中, 通常被用来做内存泄露的检查, 性能分析。

近期在使用valgrind做内存泄露, 忽略了此处testcode中的泄露提醒, 结果将代码提交上去后, 发现还是有内存的泄露, 被同事“嘲笑”了一番。

写了一小段代码, 来表述这个问题

 

class A

{

public:

  A(size_t s)

{

m_pdata = new int[s];

private:

int *m_pdata; 

} ;

 nt main()

{
    A *pa = new A(5);
    return 0;
}

 

/*****************************************************/

可以看出, 内存泄露的地方有两处, 一个出 main中, 一处是 class A 的构造函数中。 

 而再看看valgrind的提示信息
[tianduo@search041144.sqa.cm4 c++]$ valgrind --leak-check=yes ./a.out  
==4049== Memcheck, a memory error detector.
==4049== Copyright (C) 2002-2006, and GNU GPL'd, by Julian Seward et al.
==4049== Using LibVEX rev 1658, a library for dynamic binary translation.
==4049== Copyright (C) 2004-2006, and GNU GPL'd, by OpenWorks LLP.
==4049== Using valgrind-3.2.1, a dynamic binary instrumentation framework.
==4049== Copyright (C) 2000-2006, and GNU GPL'd, by Julian Seward et al.
==4049== For more details, rerun with: -v
==4049== 
==4049== 
==4049== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 5 from 1)
==4049== malloc/free: in use at exit: 28 bytes in 2 blocks.
==4049== malloc/free: 2 allocs, 0 frees, 28 bytes allocated.
==4049== For counts of detected errors, rerun with: -v
==4049== searching for pointers to 2 not-freed blocks.
==4049== checked 163,288 bytes.
==4049== 
==4049== 28 (8 direct, 20 indirect) bytes in 1 blocks are definitely lost in loss record 1 of 2
==4049==    at 0x4A06019: operator new(unsigned long) (vg_replace_malloc.c:167)
==4049==    by 0x4006AA: main (memory.cpp:14)
==4049== 
==4049== LEAK SUMMARY:
==4049==    definitely lost: 8 bytes in 1 blocks.
==4049==    indirectly lost: 20 bytes in 1 blocks.
==4049==      possibly lost: 0 bytes in 0 blocks.
==4049==    still reachable: 0 bytes in 0 blocks.
==4049==         suppressed: 0 bytes in 0 blocks.
==4049== Reachable blocks (those to which a pointer was found) are not shown.

==4049== To see them, rerun with: --show-reachable=yes 

 粗略一看, 只有  main函数的14行, 如果在测试的时候, 认为忽略这一行, 那就遗漏了 class A中的泄露点。

  

posted @ 2011-12-31 15:03  nosaferyao  阅读(456)  评论(0编辑  收藏  举报