实现自己的内存池 [英] Implement own memory pool

查看:193
本文介绍了实现自己的内存池的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要安排一定量的内存前期和使用,内存为程序的其余部分。该方案将基本上被几个字符串和结构分配内存。如何实现这一点?什么数据结构是用来存储指针和我怎么用它来给我一个具体数额?

I want to allocate a certain amount of memory upfront and use that memory for the rest of the program. The program will basically be allocating memory for a few strings and structs. How do I implement this? What data structures are used to store the pointers and how do I use it to give me a specific amount?

例如,如果我的malloc 1 MB的空间,有它在一个指针 P ,我怎么能开出从它250 KB片?

For example, if I malloc 1 MB of space and have it in a pointer p, how do I carve out a 250 KB piece from it ?

这只是意味着是一个快速和肮脏的执行情况。

This is just meant to be a quick and dirty implementation.

推荐答案

如果您希望能够内存返回到池中,它变得更加复杂。然而,对于快速和不相当那么脏的方法,你可能想实现一些code,你可以再次使用...

If you want to be able to return memory to the pool, it gets more complicated. However, for the quick and not-quite-so-dirty approach, you may want to implement some code that you can use again...

typedef struct pool
{
  char * next;
  char * end;
} POOL;

POOL * pool_create( size_t size ) {
    POOL * p = (POOL*)malloc( size + sizeof(POOL) );
    p->next = (char*)&p[1];
    p->end = p->next + size;
    return p;
}

void pool_destroy( POOL *p ) {
    free(p);
}

size_t pool_available( POOL *p ) {
    return p->end - p->next;
}

void * pool_alloc( POOL *p, size_t size ) {
    if( pool_available(p) < size ) return NULL;
    void *mem = (void*)p->next;
    p->next += size;
    return mem;
}

在我的经验,使用这样池的时候,分配许多对象,我想precalculate如何将需要的内存,这样我不浪费,但我也不想犯任何错误(喜欢不分配enoudh)。所以,我把所有的拨款code在循环中,并设置了我的池分配函数接受执行对空游泳池的虚拟分配的标志。周围循环的第二次,我已经计算出池的大小,所以我可以创建池并做真正的分配都具有相同的函数调用和没有重复code。你需要改变我的建议的池code,因为你不能做到这一点与指针算法,如果内存尚未分配。

In my experience, when using pools like this to allocate many objects, I want to precalculate how much memory will be needed so that I'm not wasteful, but I also don't want to make any mistakes (like not allocating enoudh). So I put all the allocation code inside a loop, and set up my pool allocation functions to accept a flag that performs a 'dummy' allocation on an empty pool. The second time around the loop, I have already calculated the size of the pool so I can create the pool and do the real allocations all with the same function calls and no duplicate code. You'd need to change my suggested pool code, because you can't do this with pointer arithmetic if the memory hasn't been allocated.

这篇关于实现自己的内存池的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆