mempool矿池怎么用
1. 用C编一个内存托管函数库...
使用方法:
__________________________________________
#include "mempool.h"
#include <stdio.h>
int main() {
MemPool* pool = open_pool();//这个链表储存了所有指针信息。
char* str =NEW_STR(pool, 1024);//申请内存空间,并在pool中记录。
scanf("%s", str);printf("%s\n",str);
close_pool(pool);//释放所有申请的空间
return 0;}
__________________________________________
#include <stdlib.h>
struct _MEM_TABLE_ {
void * pointer;
struct _MEM_TABLE_* next;
};
typedef struct _MEM_TABLE_ MemPool;
typedef void (*FUNC_POOL_EACH)(MemPool*);
MemPool* open_pool(void);
void close_pool(MemPool*);
MemPool* __pool_bottom(const MemPool*);
void __pool_for_each(MemPool*, FUNC_POOL_EACH);
void __pool_alloc_memset(void*,size_t);
void* alloc_pool(MemPool*, size_t);
void delloc_pool(MemPool*, void*);
#define NEW_STR(pPool,len) ((char*)alloc_pool((pPool),(len)))
#define NEW_INT(pPool) ((int*)alloc_pool((pPool),sizeof(int)))
#define NEW_DOUBLE(pPool) ((double*)alloc_pool((pPool),sizeof(double)))
#define NEW_FLOAT(pPool) ((float*)alloc_pool((pPool),sizeof(float)))
#define NEW_TYPE(pPool, tType) ((tType*)alloc_pool((pPool),sizeof(tType)))
#define DELETE(pPool,p) (delloc_pool((pPool),(p)))
MemPool* open_pool(void) {
MemPool* p = malloc(sizeof(MemPool));
if (p != NULL) {
p->pointer = NULL;
p->next = NULL;
}
return p;
}
void close_pool(MemPool* p) {
MemPool* now = p, *tmp;
while (now != NULL) {
tmp = now;
now = now->next;
if (tmp->pointer != NULL) {
free(tmp->pointer);
}
free(tmp);
}
}
void __pool_alloc_memset(void* p, size_t len) {
size_t i;
for (i = 0; i < len; i++) {
*((char*)(p+i)) = '\0';
}
}
MemPool* __pool_bottom(const MemPool* p) {
MemPool* tmp = (MemPool*)p;
if (p == NULL) return NULL;
while (tmp != NULL) {
if (tmp->next == NULL) {
break;
} else {
tmp = tmp->next;
}
}
return tmp;
}
void __pool_for_each(MemPool* pool, FUNC_POOL_EACH func) {
MemPool *now = pool, *tmp;
while(now != NULL) {
tmp = now;
now = now->next;
(*func)(tmp);
}
}
void* alloc_pool(MemPool* p, size_t l) {
MemPool *tmp = __pool_bottom(p), *pnew;
if (tmp == NULL) return NULL;
pnew = malloc(sizeof(MemPool));
if (pnew == NULL) return NULL;
pnew->next = NULL;
pnew->pointer = malloc(l);
__pool_alloc_memset(pnew->pointer, l);
tmp->next = pnew;
return pnew->pointer;
}
void delloc_pool(MemPool* pool, void * p) {
MemPool *now = pool, *parent;
if (p == NULL) {
return;
}
for(parent = now; now != NULL; parent=now, now = now->next) {
if (p == now->pointer) {
parent->next = now->next;
free(now->pointer);
free(now);
}
}
}