本帖最后由 yiluoff 于 2013-2-6 14:26 编辑
这是一个memory.cpp代码,关于申请内存的,返回s_postBufferSize的开始地址,第20行代码不理解是干什么的,求大大们帮忙解释一下。 代码如下: - void* memory::alloc(size_t Size, ALIGNMENT Align, const char* FileName, int LineNumber)
- {
- if (!Size)
- {
- return 0;
- }
- // we store the memory size requested in 24 bits
- debug_assert(Size < (1<<24), "allocating a block too large"); if (Align == ALIGN_DEFAULT)
- {
- Align = s_defaultAlignment;
- } // compute the size of the total allocation
- uint32 trueSize = Size + Align + sizeof(sMemoryBlockHeader);
- trueSize += s_preBufferSize + s_postBufferSize; // allocate the required memory
- char* pRealMem = (char*)malloc(trueSize);
- debug_assert(pRealMem, "catastrophic memory allocation error!"); // find the aligned memory position we will give back to the caller
- char* pClientMem = (char*) (pRealMem + Align + sizeof(sMemoryBlockHeader));
- pClientMem += s_preBufferSize;
- if (Align)
- {
- pClientMem = (char*)((int)(pClientMem) & ~(Align-1));
- } // we can now write the memory block header
- sMemoryBlockHeader* pHeader = getMemoryBlockHeader(pClientMem);
- pHeader->actualSize = trueSize;
- pHeader->pointerOffset = (char*)pHeader - (char*)pRealMem;#ifdef ENABLE_MEMORY_DEBUGGING
- // write the prebuffer and postbuffer
- // debug information
- sPreBufferData* pPreBufferData = (sPreBufferData*)(pHeader+1);
- pPreBufferData->nextHeader = s_topMemoryBlock;
- pPreBufferData->previousHeader = 0;
- pPreBufferData->requestedSize = Size;
- pPreBufferData->userChecksum = 0;
- pPreBufferData->fileLine = LineNumber; if (s_topMemoryBlock)
- {
- s_topMemoryBlock->previousHeader = pPreBufferData;
- }
- s_topMemoryBlock = pPreBufferData; if (FileName)
- {
- strncpy(pPreBufferData->fileName, FileName, MAX_MEMORY_FILENAME); // filename of the caller
- }
- else
- {
- strncpy(pPreBufferData->fileName, "unknown", MAX_MEMORY_FILENAME); // filename of the caller
- } uint8* prePattern = pPreBufferData->bytePattern;
- uint8* postPattern = (uint8*)pClientMem + Size;
- for (int i=0;i<memory::PATTERN_SIZE;i++)
- {
- prePattern[i]=(char)memory::PRE_PATTERN;
- postPattern[i]=(char)memory::POST_PATTERN;
- } // update our memory statistics
- s_allocCount++;
- s_totalBytesRequested += Size;
- s_totalBytesUsed += trueSize;
- s_totalBytesNeeded += (trueSize-s_preBufferSize-s_postBufferSize);
-
- s_maximumBytesRequested = maximum(s_maximumBytesRequested,s_totalBytesRequested); s_maximumBytesUsed = maximum(s_maximumBytesUsed,s_totalBytesUsed); s_maximumBytesNeeded = maximum(s_maximumBytesNeeded,s_totalBytesNeeded);#endif // return the client portion of the allocation
- return (pClientMem);
- }
复制代码第28行是内存对齐的?希望大大们给小弟讲解下。
下面是ALIGNMENT枚举
- enum ALIGNMENT
- {
- ALIGN_DEFAULT= -1,
- ALIGN_NONE = 0,
- ALIGN_4 = 4,
- ALIGN_8 = 8,
- ALIGN_16 = 16,
- ALIGN_32 = 32
- };
-
复制代码代码调用方法 - _nextOpenList = (uint16*)alloc_aligned_memory(sizeof(uint16)*m_maxCount, memory::ALIGN_32);//new(memory::ALIGN_32) int16[m_maxCount];
复制代码
这些代码是摘自《地形引擎》那本书的。
|