总体的设计思路:
首先按照内存块的大小申请N*块大小的连续内存区域。
构造内存块的双向链表,有2种,一种是空闲链表;另外一种为已经使用的链表。该双向链表也是一块固定大小的内存区域,每个链表节点存储了当前内存块的地址、该节点上一个节点以及下一个节点。
#define ut_base(TYPE) struct { TYPE *next; TYPE *prev; }__attribute__((packed)) /********************** * define memory block struct _block * *******************/ typedef struct _block{ char *data; ut_base(struct _block) base; }__attribute__((packed)) block;
内存池中存储链表的起始地址、内存块的起始地址、空闲链表的节点数、空闲链表的开始节点以及结束节点、已使用链表的节点的开始节点以及结束节点。
typedef struct _mem_pool { unsigned int blockCount; unsigned int blockSize; unsigned int freeSize; unsigned int freeCount; struct _block *freeH; struct _block *freeT; struct _block *usedH; struct _block *usedT; struct _block *pBlockHead; char *pDataHead; }__attribute__((packed)) mem_pool;
mem_pool.h
#define increment 64 /******************** * define base list * *****************/ #define ut_base(TYPE) struct { TYPE *next; TYPE *prev; }__attribute__((packed)) /********************** * define memory block struct _block * *******************/ typedef struct _block{ char *data; ut_base(struct _block) base; }__attribute__((packed)) block; /******************** * define memory pool * *****************/ typedef struct _mem_pool { unsigned int blockCount; unsigned int blockSize; unsigned int freeSize; unsigned int freeCount; struct _block *freeH; struct _block *freeT; struct _block *usedH; struct _block *usedT; struct _block *pBlockHead; char *pDataHead; }__attribute__((packed)) mem_pool; /*********************** * init a memory pool * *******************/ int pool_init(int blockSize,int blockCount); /********************* * add block to mem_pool * ******************/ int pool_block(size_t unitSize,int blockCount); /********************** * alloc memory from memory pool * ********************/ char *pool_alloc(size_t allocSize); /************************ * recyc memory from memory pool * ********************/ int pool_recyc(); /************************** * free all memory to operation system * ***********************/ void pool_free(); /*************************** * prt all list of memory pool * ************************/ void pool_prt();
mem_pool.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "mem_pool.h" static mem_pool pool; int pool_init(int blockSize,int blockCount) { mem_pool *mp=&pool; int flag=0; mp->blockCount=mp->freeCount=blockCount; mp->blockSize=blockSize; mp->freeH=mp->freeT=NULL; mp->usedH=mp->usedT=NULL; flag=pool_block(blockSize,blockCount); if(flag>0){fprintf(stderr," pool_init error ");return 1;} return 0; } int pool_block(size_t unitSize,int blockCount) { mem_pool *mp=&pool; int i=0; mp->pBlockHead=(block *)malloc(sizeof(block)*blockCount); mp->pDataHead=(char *)malloc(sizeof(char)*unitSize*blockCount); memset(mp->pDataHead,'