How does realloc know how much to copy?

后端 未结 5 1098
庸人自扰
庸人自扰 2020-12-11 15:52

how does realloc know the size of original data?

 void *realloc(void *ptr, size_t size);

So, if the implementation is like this:

         


        
5条回答
  •  悲哀的现实
    2020-12-11 16:26

    But how can I then implement realloc in my code with malloc/free/..?

    If you're already using malloc & free, why not just use realloc? else you can just have a look at the CRT source that ships with MSVC/gcc etc. (or just download it, in the case of GCC), and see how they implement it. If your running a custom allocator, then its a little more situational, eg: I use a binary bin with a slab type system, in which case realloc is simple:

    void* Reallocate(Manager* pManager, void* pBlock, size_t nSize, const char* szFile, const DWORD dwLine)
    {
        #if ( MMANAGER_NULL_TO_DEFAULT )
            if(pManager == NULL)
                pManager = MMANAGER_DEFUALT_MANAGER;
        #endif
    
        if(pBlock == NULL)
            return Allocate(pManager,nSize,szFile,dwLine);
        else if(nSize == 0)
        {
            Free(pManager,pBlock,szFile,dwLine);
            return NULL;
        }
    
        BlockHeader* pHeader = GetHeader(pBlock);
        size_t nPrevSize = pHeader->pPoolBlock->nSize;
        if(nPrevSize < nSize)
        {
            void* pNewBlock = Allocate(pManager,nSize,szFile,dwLine);
            memcpy(pNewBlock,pBlock,nPrevSize);
            PoolBlock* pPoolBlock = pHeader->pPoolBlock;
            if(pPoolBlock == NULL)
                free(pHeader);
            else
                FreeBlock(pPoolBlock,pHeader);
    
            return pNewBlock;
        }
    
        return pBlock;
    }
    

提交回复
热议问题