我想预先分配一定数量的内存,并将该内存用于程序的其余部分。该程序基本上将为一些字符串和结构分配内存。我该如何实现?什么数据结构用于存储指针,如何使用它来给我一个特定的数量?
例如,如果我malloc 1 MB的空间并将其放在指针p
中,我该如何从中创建250 KB的片段?
这只是一个快速而肮脏的实现。
答案 0 :(得分:17)
如果您希望能够将内存返回池中,则会变得更加复杂。但是,对于快速且不那么脏的方法,您可能希望实现一些可以再次使用的代码......
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;
}
根据我的经验,当使用这样的池来分配许多对象时,我想预先确定需要多少内存,这样我就不会浪费,但我也不想犯任何错误(比如不分配) enoudh)。所以我将所有分配代码放在循环中,并设置我的池分配函数以接受在空池上执行“虚拟”分配的标志。第二次围绕循环,我已经计算了池的大小,所以我可以创建池并使用相同的函数调用进行实际分配,并且没有重复的代码。您需要更改我建议的池代码,因为如果尚未分配内存,则无法使用指针算法执行此操作。
答案 1 :(得分:-2)
使用内存池进行内存管理 -
内存池是预分配相同大小的内存块的方法。 例如,同一类的各种对象。因此,它更多的是设计你的软件的“记忆模型”。
示例 - 动画gif具有各种帧。假设每个帧只需要最大1024 KB。 此外,如果我们知道我们只能有两个帧,那么我们可以通过为每个帧预先分配内存来避免碎片。
[注意] - 在我们了解系统在设计时的行为的情况下,内存池更适用。 因此,内存池概念并不适用于所有地方。 // ================================================ ============================ //名称:MemoryPool.cpp //作者: //版本: //版权:SHREYAS JOSHI //描述: // ================================================ ============================
#include <iostream>
#include <malloc.h>
struct memPool
{
private:
char *m_poolPtr;
char *m_nextAvailAddr;
char *m_endAddr;
public:
/** Methods for the structure **/
void poolCreate(size_t size);
void poolDestroy();
void * poolAlloc(size_t size);
memPool():m_poolPtr(NULL),m_nextAvailAddr(NULL),m_endAddr(NULL)
{
std::cout<<"memPool constructor Invoked"<<std::endl;
}
~memPool()
{
std::cout<<"memPool Destructor Invoked"<<std::endl;
m_poolPtr = NULL;
m_nextAvailAddr = NULL;
m_endAddr = NULL;
}
};
/** Create a Pool of memory - makes a program hassle free of doing malloc multiple times **/
/** Also, Fragmentation can be avoided with the Memory Pool concept **/
/** A pool concept is useful, when you know at design time.how much memory is required for
the similar type of objects in total**/
void memPool::poolCreate(size_t size)
{
m_poolPtr = (char *) malloc(size);
if(m_poolPtr == NULL)
{
std::cout<<"Pool Create Failed"<<std::endl;
//printf("Pool Create Failed \r\n");
}
m_nextAvailAddr = m_poolPtr;
/** note the addressing starts from zero - thus you have already counted zero**/
m_endAddr = m_poolPtr + size - 1;
//printf("The Pool Head Pointer = %p \r\n",m_poolPtr);
std::cout<<"Pool Head Pointer = "<<static_cast<void *>(m_poolPtr)<<std::endl;
//printf("The Pool m_nextAvailAddr = %p \r\n",m_nextAvailAddr);
std::cout<<"Pool m_nextAvailAddr = "<<static_cast<void *>(m_nextAvailAddr)<<std::endl;
//printf("The Pool m_endAddr = %p \r\n",m_endAddr);
std::cout<<"Pool m_endAddr = "<<static_cast<void *>(m_endAddr)<<std::endl;
}
/** Destroy the entire pool in one shot ********/
void memPool::poolDestroy()
{
free(m_poolPtr);
/** Remember free first then assign to NULL **/
m_poolPtr = NULL;
/** Update Housekeeping--data structure **/
m_nextAvailAddr = NULL;
m_endAddr = NULL;
}
/** Allocate some space from the pool ********/
/** Check if the space is available or not **/
/** Do the housekeeping - update the nextAvail Addr in the structure**/
void * memPool::poolAlloc(size_t size)
{
void *mem = NULL;
if( (m_endAddr != NULL) && (m_nextAvailAddr != NULL))
{
/** This is according to fencing problem - add 1 when you are find a difference of sequence to calculate the space within **/
size_t availableSize = m_endAddr - m_nextAvailAddr + 1;
/** check for the availability **/
if(size > availableSize )
{
//std::cout<<"Warning!! the available size = "<<availableSize<< "requested size = "<<size<<std::endl;
printf("Warning!! the available size = %u and requested size = %u \r\n",availableSize, size);
mem = NULL;
}
else
{
/** store the available pointer to the user**/
mem = m_nextAvailAddr;
//printf("The user return pointer is = %p \r\n ",mem);
std::cout<<"The user return pointer is = "<<static_cast <void *>(mem)<<std::endl;
/*** advance the next available pointer **/
m_nextAvailAddr += size;
//printf("The next available pointer is = %p \r\n ",m_nextAvailAddr);
std::cout<<"The next available pointer is = "<<static_cast<void *>(m_nextAvailAddr)<<std::endl;
}
}
return mem;
}
int main(int argc, char *argv[])
{
memPool gifAnimatedImageFramesBlk;
/** Let's say each frame needs 512 kb **/
char *gifFrame1 = NULL;
char *gifFrame2 = NULL;
char *gifFrame3 = NULL;
/** 1 MB Pool for the GIF IMAGE FRAMES **/
gifAnimatedImageFramesBlk.poolCreate(1024*1024*1024);
/*** 512 KB **/
gifFrame1 = (char *)gifAnimatedImageFramesBlk.poolAlloc(512*1024*1024);
//printf("Got the gifFrame1..pointer- == %p \r\n ",gifFrame1);
std::cout<<"Got the gifFrame1..pointer- == "<<static_cast<void *>(gifFrame1)<<std::endl;
/** again 512 MB **/
gifFrame2 = (char *)gifAnimatedImageFramesBlk.poolAlloc(512*1024*1024);
std::cout<<"Got the gifFrame2..pointer- == "<<static_cast<void *>(gifFrame2)<<std::endl;
//printf("Got the gifFrame2..pointer- == %p \r\n ",gifFrame2);
/*************Exhausted the pool memory now **************/
/** This will fail ****************/
gifFrame3 = (char *)gifAnimatedImageFramesBlk.poolAlloc(1);
std::cout<<"Got the gifFrame3..pointer- == "<<static_cast<void *>(gifFrame3)<<std::endl;
//printf("Got the gifFrame3..pointer- == %p \r\n ",gifFrame3);
/*****Destroy the Pool now *****************/
gifAnimatedImageFramesBlk.poolDestroy();
gifFrame3 = (char *)gifAnimatedImageFramesBlk.poolAlloc(1);
std::cout<<"Got the gifFrame3..pointer- == "<<static_cast<void *>(gifFrame3)<<std::endl;
//printf("Got the gifFrame3..pointer- == %p \r\n ",gifFrame3);
gifFrame3 = (char *)gifAnimatedImageFramesBlk.poolAlloc(1);
std::cout<<"Got the gifFrame3..pointer- == "<<static_cast<void *>(gifFrame3)<<std::endl;
//printf("Got the gifFrame3..pointer- == %p \r\n ",gifFrame3);
return 0;
}
[注意] - 为了使用ostream :: operator&lt;&lt;在C ++中打印char *的值,char *应该被类型化为void * static_cast(pointer_Name)。问题是如果C ++编译器看到char *,那么它会查找NULL终止符 - '\ 0'。 在这种情况下,没有NULL终止符'\ 0'。所以,你会看到一个未定义的行为。
内存池的优点