valgrind 使用

来源:互联网 发布:交互式电子白板软件 编辑:程序博客网 时间:2024/05/12 22:32

<!--@page { margin: 2cm }H1 { margin-top: 0.6cm; margin-bottom: 0.58cm; page-break-inside: avoid }H1.western { font-family: "DejaVu Serif", serif; font-size: 12pt }H1.cjk { font-family: "DejaVu Sans"; font-size: 12pt; font-style: normal; font-weight: bold }H1.ctl { font-size: 22pt; font-weight: bold }P { margin-bottom: 0.21cm }-->

[1]分析内存泄露和内存越界

test.c

  1 #include <stdio.h>

 

  2
  3 void f(void)
  4 {
  5     int *x = malloc(sizeof(int) * 10);
  6     x[10] = 0;
  7 }
  8
  9   int main(void)
 10 {
 11     f();
 12     return 0;
 13 }
lengmian@ubuntu:~/akaedu/hwp/search$ valgrind --tool=memcheck --leak-check=full ./val_test==7465== Memcheck, a memory error detector
==7465== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.
==7465== Using Valgrind-3.6.0.SVN-Debian and LibVEX; rerun with -h for copyright info
==7465== Command: ./val_test
==7465==
==7465== Invalid write of size 4              // 这一段数组越界,
Invalid write of size 4 表示这个意思??? 固定的说明形式??

                                                                                ---- 写入的内存大小不对应,发生了内存越界<!--@page { margin: 2cm }P { margin-bottom: 0.21cm }-->

==7465==    at 0x80483FF: f (val_test.c:6)      //  错误位置
==7465==    by 0x8048411: main (val_test.c:11)
==7465==  Address 0x4194050 is 0 bytes after a block of size 40 alloc'd
==7465==    at 0x4024F20: malloc (vg_replace_malloc.c:236)
==7465==    by 0x80483F5: f (val_test.c:5)               
<!--@page { margin: 2cm }P { margin-bottom: 0.21cm }-->---- 第5行漏了40个字节的内存

==7465==    by 0x8048411: main (val_test.c:11)
==7465==
==7465==
==7465== HEAP SUMMARY:                                  //动态申请空间,没有释放
==7465==     in use at exit: 40 bytes in 1 blocks
==7465==   total heap usage: 1 allocs, 0 frees, 40 bytes allocated
==7465==
==7465== 40 bytes in 1 blocks are definitely lost in loss record 1 of 1
==7465==    at 0x4024F20: malloc (vg_replace_malloc.c:236)
==7465==    by 0x80483F5: f (val_test.c:5)                    //错误位置
==7465==    by 0x8048411: main (val_test.c:11)
==7465==
==7465== LEAK SUMMARY:
==7465==    definitely lost: 40 bytes in 1 blocks
==7465==    indirectly lost: 0 bytes in 0 blocks
==7465==      possibly lost: 0 bytes in 0 blocks
==7465==    still reachable: 0 bytes in 0 blocks
==7465==         suppressed: 0 bytes in 0 blocks
==7465==
==7465== For counts of detected and suppressed errors, rerun with: -v
==7465== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 13 from 8)