内存池简易版 c语言
#ifndef X_MEMORY_H #define X_MEMORY_H #include <stdlib.h> #include <stdio.h> #include <memory.h> typedef enum { ErrorUnknown, NoError, ErrorInit }XMemErrorCode; #ifdef __cplusplus extern "C" { #endif int initMemory(int size); void* xmalloc(int size); void xfree(void* data); #ifdef __cplusplus } #endif #endif
#include "xmemory.h" typedef struct { void* pre; void* next; int size; }stBlock; static stBlock* head = NULL; int initMemory(int size) { stBlock* tail = NULL; char* memhead = (char*)malloc(size); if(NULL == memhead) return ErrorInit; memset(memhead, , size); head = (stBlock*)memhead; head->pre = NULL; head->next = memhead + size - sizeof(stBlock); head->size = ; tail = head->next; tail->pre = head; tail->next = NULL; tail->size = ; return NoError; } void* xmalloc(int size) { stBlock* blk = head; stBlock* nblk = NULL; stBlock* tmpblk = NULL; char* ret = NULL; int ntry = ; do { int validsize = (char*)blk->next - (char*)blk - sizeof(stBlock)* - blk->size; if(validsize >= size){ nblk = (stBlock*)((char*)blk+sizeof(stBlock)+blk->size); nblk->size = size; nblk->next = blk->next; nblk->pre = blk; blk->next = nblk; break; }else{ blk = blk->next; } } while (blk->next); if (NULL == nblk) { return NULL; } ret = (char*)nblk+sizeof(stBlock); memset(ret, , size); return ret; } void xfree(void* data) { stBlock* blk = head; stBlock* preblk = NULL; do { if ((char*)blk+sizeof(stBlock) == data) { preblk = blk->pre; preblk->next = blk->next; break; }else { blk = blk->next; } } while (blk); }
相关推荐
yongzhang 2020-05-25
paopao00 2020-02-16
gzx0 2020-01-31
Annihilation 2011-08-15
fatansitic 2011-07-27
追寻水中桥 2019-10-19
lglovejava 2016-04-19
帅性而为号 2019-07-11
二十不悔三十而立 2016-07-10
了不起的厂长 2019-06-28
Lincain 2019-06-26
mfcaiblog 2011-08-16
ljlxyf 2016-07-13