首页 技术 正文
技术 2022年11月15日
0 收藏 462 点赞 4,428 浏览 1415 个字

1. 题目

改造malloc和free函数,使C语言能自动发现泄漏的内存,在程序退出时打印中遗漏的内存地址和大小。

2. 思路

用一个链表来记录已经分配的内存地址。在malloc时,把分配的内存地址和大小插入链表;在free时,找到链表中相应结点,删除该结点。程序退出时,打印出链表中的结点。

上述思路有一个缺陷:删除结点时,需要遍历链表,如何才能变成常数时间能完成的操作?

方法是:在malloc时,多分配一块区域,用来记录链表结点的位置。

3. 代码

//Code 1
#include <stdlib.h>typedef struct _PtrNode
{
struct _PtrNode* prev;
struct _PtrNode* next;
void* locatedPtr;
int size;
}PtrNode;PtrNode* gRecordList;void InitList()
{
gRecordList = (PtrNode*)malloc(sizeof(PtrNode));
gRecordList->prev = NULL;
gRecordList->next = NULL;
} void InsertNode(PtrNode* pNode)
{
if (NULL != gRecordList->next)
{
gRecordList->next->prev = pNode;
}
pNode->next = gRecordList->next;
gRecordList->next = pNode;
pNode->prev = gRecordList;
} void DeleteNode(PtrNode* pNode)
{
if (NULL != pNode->next)
{
pNode->next->prev = pNode->prev;
}
pNode->prev->next = pNode->next;
free(pNode);
}void PrintLeek()
{
PtrNode* pNode;
for(pNode = gRecordList->next; pNode != NULL; pNode = pNode->next)
{
printf("leek:%x,%d\n", pNode->locatedPtr, pNode->size);
}
}void* MyMalloc(int size)
{
void* ptr = malloc(size + sizeof(PtrNode*));
PtrNode* pNode = (PtrNode*)malloc(sizeof(PtrNode));
pNode->locatedPtr = ptr;
pNode->size = size;
*(PtrNode**)(ptr + size) = pNode;
InsertNode(pNode);
return ptr;
}#define MyFree(pHandler) \
do {\
int size = sizeof(*pHandler); \
PtrNode* pNode = *(PtrNode**)((void*)pHandler + size);\
DeleteNode(pNode); \
free(pHandler);\
}while(0)int main()
{
InitList();
int* p = (int*)MyMalloc(sizeof(int));
p = (int*)MyMalloc(sizeof(int));
PtrNode* p2 = (PtrNode*)MyMalloc(sizeof(PtrNode));
MyFree(p);
PrintLeek();
}
上一篇: 学习笔记之#pragma
下一篇: html5刮刮卡
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,031
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,520
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,368
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,148
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,781
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,860