valgrind内存泄露和线程竞态检测,腾讯Android开发面试

2、callgrind:检测程序代码的运行时间和调用过程,以及分析程序性能。

3、cachegrind:分析CPU的cache命中率、丢失率,用于进行代码优化。

4、helgrind:用于检查多线程程序的竞态条件。

5、massif:堆栈分析器,指示程序中使用了多少堆内存等信息。

6、lackey:

7、nulgrind:

这几个工具的使用是通过命令:valgrand --tool=name 程序名来分别调用的,当不指定tool参数时默认是 --tool=memcheck

二 Valgrind工具详解

1.Memcheck

最常用的工具,用来检测程序中出现的内存问题,所有对内存的读写都会被检测到,一切对malloc、free、new、delete的调用都会被捕获。所以,它能检测以下问题:

1、对未初始化内存的使用;

2、读/写释放后的内存块;

3、读/写超出malloc分配的内存块;

4、读/写不适当的栈中内存块;

5、内存泄漏,指向一块内存的指针永远丢失;

6、不正确的malloc/free或new/delete匹配;

7、memcpy()相关函数中的dst和src指针重叠。

这些问题往往是C/C++程序员最头疼的问题,Memcheck能在这里帮上大忙。

例如:

[plain]  view plain copy

  1. #include <stdlib.h>

  2. #include <malloc.h>

  3. #include <string.h>

  4. void test()

  5. {

  6. int *ptr = malloc(sizeof(int)*10);

  7. ptr[10] = 7; // 内存越界

  8. memcpy(ptr +1, ptr, 5); // 踩内存

  9. free(ptr);

  10. free(ptr);// 重复释放

  11. int *p1;

  12. *p1 = 1; // 非法指针

  13. }

  14. int main(void)

  15. {

  16. test();

  17. return 0;

  18. }

将程序编译生成可执行文件后执行: valgrind --leak-check=full ./程序名

输出结果如下:

==4832== Memcheck, a memory error detector

==4832== Copyright © 2002-2010, and GNU GPL’d, by Julian Seward et al.

==4832== Using Valgrind-3.6.1 and LibVEX; rerun with -h for copyright info

==4832== Command: ./tmp

==4832==

==4832== Invalid write of size 4      // 内存越界

==4832==    at 0x804843F: test (in /home/yanghao/Desktop/testC/testmem/tmp)

==4832==    by 0x804848D: main (in /home/yanghao/Desktop/testC/testmem/tmp)

==4832==  Address 0x41a6050 is 0 bytes after a block of size 40 alloc’d

==4832==    at 0x4026864: malloc (vg_replace_malloc.c:236)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值