在C中初始化内存分配器

时间:2017-09-09 20:52:02

标签: c pointers memory-management malloc dynamic-memory-allocation

我试图实现一个init_allocator()函数来初始化内存分配器并使_length个字节的一部分可用。分配器使用_basic_block_size作为其最小分配单元。该函数返回分配器可用的内存量。如果发生错误,则返回0

这是我到目前为止所做的:

int memAvail;  // amount of memory to be made available to allocator

unsigned int init_allocator(unsigned int _basic_block_size, unsigned int _length){
    if (_basic_block_size < _ length){
        memAvail = _length/_basic_block_size;
        return memAvail;
    }
    else{           
        return 0;
    }   
}

我不知道这是否是正确的实现,但对我来说似乎是对的。有什么我做错了吗?我应该使用指针吗?任何建议将不胜感激。

1 个答案:

答案 0 :(得分:2)

这是Kernighan and Ritchie

中第5.4章的示例内存分配器
#include<stdio.h>

#define ALLOCSIZE 10000 

static char allocbuf[ALLOCSIZE]; 
static char *allocp=allocbuf; 

/* Return pointer to n characters */
char *alloc(int n)
{
   if(allocbuf+ALLOCSIZE-allocp>=n){
       // It fits 
       allocp+=n;
       return allocp-n;
   }else 
       // Not enough room
       return 0;
}

allocbuf是存储字符的内存缓冲区,因为这是一个char分配器。 *alloccp是指向下一个自由位置的指针,最初是allocbuf的第一个(即第0个)元素。 *alloc返回指向allocbuf中第一个点的指针,程序将存储n个字符。

这可以很容易地转换为其他数据类型,它演示了可能的简单分配器设计原则。澄清您的要求,我可以添加内容。