使用memwatch进行内存调试

来源:互联网 发布:d3.js 框选 编辑:程序博客网 时间:2024/04/28 13:16

1、memwatch介绍

memwatch可以跟踪程序中的内存泄漏和错误,提供结果日志记录,能检测双重释放、错误释放、没有释放的内存、上溢和下溢等。


2、使用memwatch步骤

1)在代码中加入头文件memwatch.h

2)程序的代码与memwatch.c一起编译、链接

3)使用gcc编译器进行编译时要定义宏MEMWATCH、MEMWATCH_STDIO,即在编译程序时增加“-DMEMWATCH -DMEMWATCH_STDIO”标志。


3、使用实例

1)程序源代码

#include <stdlib.h>
#include <stdio.h>
#include "memwatch.h" //必须包含此头文件


int main(void)
{
        char *ptr1 = NULL;
        char *ptr2 = NULL;


        ptr1 = (char *)malloc(5);
        ptr2 = (char *)malloc(5);
        ptr1[5] = 'A';


        ptr2 = ptr1;


        free(ptr2);
        free(ptr1);


        return 0;
}
    


2)makefile内容

CFLAGS = -DMEMWATCH -DMEMWATCH_STDIO                //不可缺少


all:
        gcc $(CFLAGS) -o test test.c memwatch.c 


clean:
        rm -rf test



3)生成的memwatch.log中的内容

============= MEMWATCH 2.69 Copyright (C) 1992-1999 Johan Lindh =============


Started at Thu Nov  3 14:54:39 2016


Modes: __STDC__ 64-bit mwDWORD==(unsigned long)
mwROUNDALLOC==8 sizeof(mwData)==32 mwDataSize==32


overflow: <3> test.c(17), 5 bytes alloc'd at <1> test.c(10)                       //5 bytes alloc'd...表示程序第10行分配了5个字节的空间,在第17行识别到错误
double-free: <4> test.c(18), 0x9c651e0 was freed from test.c(17)      //双重释放


Stopped at Thu Nov  3 14:54:39 2016


unfreed: <2> test.c(11), 5 bytes at 0x9c65220   {FE FE FE FE FE .. .. .. .. .. .. .. .. .. .. .. .....}     //未释放内存,表示在程序11行分配


Memory usage statistics (global):
  N)umber of allocations made: 2
  L)argest memory usage      : 10
  T)otal of all alloc() calls: 10
 U)nfreed bytes totals      : 5


0 0
原创粉丝点击