主要是解决自己分配的内存忘记释放的问题,自己定义了几个函数取代了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;
}
责任编辑:小草