Implement own memory pool

后端 未结 2 1064
走了就别回头了
走了就别回头了 2020-12-13 20:45

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

2条回答
  •  半阙折子戏
    2020-12-13 21:14

    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

    1. You can avoid fragmentation of memory. Even if the system has required memory space, the malloc() will fail when the desired contigous block size is not available.
    2. The space is reserved, and the frequent malloc() and free() is avoided. This will save time.
    3. When malloc() is called for many sub-blocks, the administrative/meta data is associated with each allocated sub-blocks. This will consume unnecessary space. Instead, one big block allocation will avoid the multiple administrative/meta data.
    4. If the memory space is restricted, then it is easy to investigate for the memory leaks. If memory is exhausted in Pool, then memory pool will return NULL. Thus, you can isolate a memory leak problem easily.

提交回复
热议问题