神经科学 2018-01-24
#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); }