mtrace检查内存泄露

mtrace内存泄漏检测:

1.安装mtrace命令:

yum install glibc-utils

2.代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/* mtrace 头文件 */
#include <mcheck.h>

int main(int argc, char *argv[])
{
     /* 设置环境变量, mtrace保存位置 */
        setenv("MALLOC_TRACE", "mtrace_output.txt", 1);
        mtrace();   /* 打开 */

        char *buff = NULL;
        int size = 128;

        buff = malloc(size);

        if (NULL == buff)
                return -1;

        memset(buff, 0, size);
        sprintf(buff, "hello, world.");

        printf("malloc buff:%s\n", buff);

        if (argc > 1)
        {
                printf("free buff.\n");
                free(buff);
        }

        muntrace();  /* 关闭 */
        return 0;
}

3.编译与运行结果

[root@localhost test]# gcc -g mtrace.c -o mtrace_test
[root@localhost test]# ./mtrace_test
malloc buff:hello, world.
[root@localhost test]# mtrace mtrace_test mtrace_output.txt

Memory not freed:
-----------------
          Address    Size    Caller
0x0000000001e435c0    0x80  at /root/test/mtrace.c:15
[root@localhost test]# 
[root@localhost test]# ./mtrace_test 123
malloc buff:hello, world.
free buff.
[root@localhost test]# mtrace mtrace_test mtrace_output.txt
No memory leaks.
[root@localhost test]# 

这个可以定位到发生内存泄漏的那句代码

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值