码迷,mamicode.com
首页 > 编程语言 > 详细

内存池简易版 c语言

时间:2018-01-24 19:56:47      阅读:226      评论:0      收藏:0      [点我收藏+]

标签:run   stdio.h   memset   else   ifd   void   int   post   class   

#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);
}

 

内存池简易版 c语言

标签:run   stdio.h   memset   else   ifd   void   int   post   class   

原文地址:https://www.cnblogs.com/larkin/p/8342887.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!