void *MemRealloc (void * buffer, unsigned int size, char * var, char * pszFile, int nLine) { void *newbuffer = NULL; #if !DBG_MALLOC if (!size) MemFree (buffer); else if (!buffer) newbuffer = MemAlloc (size, var, pszFile, nLine, 0); else if (!(newbuffer = realloc (buffer, size))) { #if TRACE con_printf (CON_MALLOC, "reallocating %d bytes in %s:%d failed.\n", size, pszFile, nLine); #endif } #else if (!bMemInitialized) MemInit (); if (!size) MemFree (buffer); else { newbuffer = MemAlloc (size, var, pszFile, nLine, 0); if (FindMemBlock (buffer) >= 0) { memcpy (newbuffer, buffer, *(((int *) buffer) - 1)); MemFree (buffer); } } #endif return newbuffer; }
/* @ Function: * allocate memory of specified size from memory pool for users * @ Arguments: * size of wanted memory (unsigned long long) * @ Return: * pointer to the allocated memory for users (void*) * the memory has been initialized with value "0". * @ Basic Algorithm: * 1) make sure enough memory left in memory pool to satify the users, * by sometimes allocating new memory blocks from the OS. * 2) allocate memory by changing used memory offset and updating memory pool's status. */ void* MemPool::Alloc( ull_t ullMemSize ) { void* p_vdMem = NULL; /* wrong input data range, return null pointer */ if( ullMemSize <= 0 ) return NULL; /* find the block from which the memory will be allocated */ MemBlock* stMemBlock = FindMemBlock( ullMemSize ); if( !stMemBlock ) { return NULL; } /* allocate the requested memory from the found block, and update mempool's status */ p_vdMem = ( void* ) ( ( unsigned char* ) stMemBlock->vdMem + stMemBlock->ullMemUsed ); memset( p_vdMem, 0, sizeof( unsigned char ) * ullMemSize ); stMemBlock->ullMemUsed += ullMemSize; ullMemUsedSize += ullMemSize; /* update maximum range of available memory blocks */ while( ullMemBlockLeftIndex < ullMemBlockRightIndex ) { MemBlock* p_stTmpMemBlk = mpstMemBlocks[ullMemBlockLeftIndex]; ull_t ullAvailMemSz = p_stTmpMemBlk->ullMemSize - p_stTmpMemBlk->ullMemUsed; ull_t ullDynamicThresh = ( ull_t ) ( ullMemBlockMaxSize * 0.01 ); ull_t ullStaticThresh = 256; if( ullAvailMemSz > ullDynamicThresh || ullAvailMemSz > ullStaticThresh ) { break; } ++ullMemBlockLeftIndex; } return p_vdMem; }
int UnregisterMemBlock (void *p) { int i = FindMemBlock (p); if ((i >= 0) && (i < --nMemBlocks)) memBlocks [i] = memBlocks [nMemBlocks]; return i; }