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
Memory Management using Memory Pool -
Memory Pool is the way to pre-allocate the blocks of memory of the same size. For example, various objects of the same class. Thus, it is more about designing the 'Memory Model' ofyour software.
Example - An animated gif has various frames. Let's say each frame needs maximum 1024 KB only. Also, if we know that we can have maximum two frames only, then we can avoid fragmentation by pre-allocating the memory for each frame.
[note] - Memory Pool is more applicable where we know the behaviour of the system at design time. Thus, memory pool concept is not applicable everywhere. //============================================================================ // Name : MemoryPool.cpp // Author : // Version : // Copyright : SHREYAS JOSHI // Description : //============================================================================
#include
#include
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"<(gifFrame1)<(gifFrame2)<(gifFrame3)<(gifFrame3)<(gifFrame3)<
[note] - In order to print the value of char * in C++ using ostream::operator<<, the char * should be typecasted to void * using static_cast (pointer_Name). The problem is that if the C++ compiler sees the char *, then it looks for the NULL terminator - '\0'. In this case, there is no NULL terminator '\0'. So, you will see an undefined behaviour.
Advantages of Memory Pool