C语言实现内存泄漏检测模块

博客介绍了C语言内存泄漏检测模块的实现及测试例程,同时强调注意事项,若在多线程中使用该检测模块,要保证g_record[SIZE]互斥使用,即进行互斥操作。

实现检测模块

/*文件 mleak.h*/
#ifndef _MLEAK_H_
#define _MLEAK_H_

#include <stdio.h>
#include <malloc.h>

#define MALLOC(n) my_malloc(n,__FILE__,__LINE__)
#define FREE(p) my_free(p)

void * my_malloc(size_t n,const char* file,const int line);
void my_free(void *p);
void PRINT_LEAK_INFO();

#endif


/*文件 mleak.c*/

#include "mleak.h"

#define SIZE 256

typedef struct
{
    void * pointer;
    int size;
    const char* file;
    int line;
}MY_ITEM;

static MY_ITEM g_record[SIZE];//如果存在多线程的情况一定要注意互斥操作!!!

void * my_malloc(size_t n,const char* file,const int line)
{
    void * ret = malloc(n);
    if (ret != NULL)
    {
        int i = 0;
        for (i = 0; i < SIZE; i++)
        {
            if (g_record[i].pointer == NULL)
            {
                g_record[i].pointer = ret;
                g_record[i].size = n;
                g_record[i].file = file;
                g_record[i].line = line;
                break;
            }
        }
        
    }
    return ret;
}
void my_free(void *p)
{
   if (p != NULL)
    {
        int i = 0;
        for (i = 0; i < SIZE; i++)
        {
            if (g_record[i].pointer == p)
            {
                g_record[i].pointer = NULL;
                g_record[i].size = 0;
                g_record[i].file = NULL;
                g_record[i].line = 0;

                free(p);

                break;
            }
        }
        
    }
}
void PRINT_LEAK_INFO()
{
    int i = 0;
    printf("Potential Memory Leak Info:\n");

    for (i = 0; i < SIZE; i++)
    {
        if (g_record[i].pointer != NULL)
        {
            printf("Address:%p,size:%d,Location:%s:%d\n",
                  g_record[i].pointer,g_record[i].size,g_record[i].file,g_record[i].line);
        }
        
    }
    
}

测试例程

#include "mleak.h"


int main()
{
    
    int *test_p = MALLOC(sizeof(int)*4);
    PRINT_LEAK_INFO();

    return 0;
}

 

注意事项:如果在多线程用使用,一定要保证g_record[SIZE]互斥使用,即保证使用自定义检测模块时要保证互斥操作

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Rookie Linux

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值