内存泄漏检测工具-memwatch与mtrace

推荐链接:
(1)https://elinux.org/Memory_Debuggers
(2)https://linux.cn/article-7354-1.html

测试程序:

[root@localhost ~/memwatch/memwatch-2.71/test]
# cat test.c
//  test memwatch    
#include 
#include "memwatch.h"

void
func(void)
{
    char *ptr = NULL;
    int len = 3;

    ptr = (char *)malloc(len * sizeof(char));
    if (NULL == ptr) {
        printf("malloc err\n"); 
    }
    free(ptr);
}

void
mem_check_init(void)
{
    mwInit();
}

void
mem_check_finish(void)
{
    mwTerm();
}

int
main(int argc, char *const argv[])
{
    mem_check_init();
    printf("start\n");
    func();
    printf("end\n");
    mem_check_finish();
    return 0;
}
[root@localhost ~/memwatch/memwatch-2.71/test]
# cat test2.c 
// test mtrace
#include 
#include 
#include 

void
func(void)
{
    char *ptr = NULL;
    int len = 3;

    ptr = (char *)malloc(len * sizeof(char));
    if (NULL == ptr) {
        printf("malloc err\n"); 
    }
    free(ptr);
}

void
mem_check_init(void)
{
    mtrace();
}

void
mem_check_finish(void)
{
    muntrace();
}

int
main(int argc, char *const argv[])
{
    mem_check_init();
    printf("start\n");
    func();
    printf("end\n");
    mem_check_finish();
    return 0;
}

编译方法:

[root@localhost ~/memwatch/memwatch-2.71/test]
# cat Makefile 
test:
        gcc -g -DMEMWATCH -DMW_STDIO test.c memwatch.c 
test2:
        gcc -g test2.c 

clean:
        rm -rf a.out *.log

memwatch能够测试:
(1)内存没有释放
eg: 只有malloc,没有free
(2)内存多次释放
eg:同一指针,多次free
(3)内存下溢
eg:ptr[-1] = 1;
(4)内存上溢
eg: ptr[len] = 1;

mtrace能够测试:
(1)内存没有释放
eg: 只有malloc,没有free
(2)内存多次释放
eg:同一指针,多次free

你可能感兴趣的:(内存泄漏检测工具-memwatch与mtrace)