主要是解决自己分配的内存忘记释放的问题,自己定义了几个函数取代了malloc,calloc,realloc,free这几个函数,尽量跟原有用法一致。
头文件mypool.h
#ifndef _MYPOOL_H
#define _MYPOOL_H
struct Node
{
struct Node *preNode;//前一个节点
struct Node *nextNode;//后一个节点
void **varAddr;//存储指针变量的地址
int size;
char freed;
};
struct Chain
{
struct Node *first;
struct Node *last;
int size;
};
void InitChain();
struct Node* InitNode(struct Node *pn);
int Push(struct Node *pn);
int RemoveChain(void **id);
int FreeChain();
void* MyMalloc(void **p,int size);
void* MyCalloc(void **p,int nsize,int usize);
void* MyRealloc(void **p,int size);
void MyFree(void **p);
#endif
实现代码:mypool.c
/********************************/
/*这些代码主要是实现对自己分配的内存的管理,主要是为了防止在程序关闭后还有忘记释放的内存;*/
/*这块代码并不涉及对内存区块的分配管理。*/
/* 作者:jackyvan ,Email:jackyyvan@gmail.com */
/********************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "mypool.h"
static struct Chain chain;//定义一个链表的静态变量
/*初始化链表*/
void InitChain()
{
chain.first=NULL;
chain.last=NULL;
chain.size=0;
}
/*初始化一个链表上的节点*/
struct Node* InitNode(struct Node *pn)
{
pn=malloc(sizeof(struct Node));
if(pn==NULL)
return NULL;
pn->preNode=NULL;
pn->nextNode=NULL;
pn->freed=0;
pn->varAddr=0;
pn->size=0;
return pn;
}
/*加入一个新的内存分配的节点*/
int Push(struct Node *pn)
{
struct Node *last=chain.last;
struct Node *first=chain.first;
if(first==NULL)
{
chain.first=pn;
chain.last=pn;
}
else
{
chain.last->nextNode=pn;
pn->preNode=chain.last;
chain.last=pn;
}
chain.size++;
return 1;
}
/*
从链表中移除一个节点
*/
int RemoveChain(void **id)
{
struct Node *first=chain.first;
struct Node *tp1=NULL,*tp2=NULL;
if(first==NULL)
return 0;
while(first)
{
if((long)first->varAddr==(long)id)
{
tp1=first->preNode;
tp2=first->nextNode;
if(tp1)
{
if(tp2)
{
tp1->nextNode=tp2;
tp2->preNode=tp1;
}
else
{
tp1->nextNode=NULL;
chain.last=tp1;
}
}
else
{
tp2->preNode=NULL;
chain.first=tp2;
}
free(first);
chain.size--;
break;
}
first=first->nextNode;
}
return 1;
}
责任编辑:小草