#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, 0, size); head = (stBlock*)memhead; head->pre = NULL; head->next = memhead + size - sizeof(stBlock); head->size = 0; tail = head->next; tail->pre = head; tail->next = NULL; tail->size = 0; return NoError; } void* xmalloc(int size) { stBlock* blk = head; stBlock* nblk = NULL; stBlock* tmpblk = NULL; char* ret = NULL; int ntry = 1; do { int validsize = (char*)blk->next - (char*)blk - sizeof(stBlock)*2 - 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, 0, 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); }
原文地址:https://www.cnblogs.com/larkin/p/8342887.html
时间: 2024-10-21 23:56:45