gpt4 book ai didi

c++ - 对齐内存分配器 : memory corruption (game engine architecture[Jason Gregory])

转载 作者:搜寻专家 更新时间:2023-10-31 01:43:49 25 4
gpt4 key购买 nike

我刚刚在读Game Engine Architecture by Jason Gregory S.212,当我偶然发现他分配对齐内存的代码时。我认为他正在产生内存损坏并使用以下代码自行尝试:

void* myalloc( unsigned size )
{
// this will not return a valid memory address but its ok since
// it will never be dereferenced! its just to check what if a real malloc would
// return this obviously UNALIGNED memory address
return reinterpret_cast<void*>( 0x00001 );
}
void* allocatedAligned( unsigned size_bytes, unsigned alignment )
{
unsigned expandedSize_bytes = size_bytes + alignment;
unsigned rawAddress = (unsigned)myalloc( expandedSize_bytes );

unsigned mask = alignment - 1;
unsigned misalignment = rawAddress & mask;
unsigned adjustment = alignment - misalignment;

unsigned alignedAddress = rawAddress + adjustment;

unsigned* ptrAdjustment = reinterpret_cast<unsigned*>( alignedAddress - 4 );
//*ptrAdjustment = adjustment; //Corruption here
//return reinterpret_cast<unsigned*>( alignedAddress ); this is what jasons function normally returns
return ptrAdjustment;
}

int main()
{
void* ptr = allocatedAligned( 4, 4 );
std::cout << ptr << std::endl; // this shouldn't print an address lower than 0x0001
return 1;
}

对齐工作正常,但我不得不反对 *ptrAdjustment = adjustment 行,因为恕我直言,它破坏了内存。它在从 myalloc() 收到的地址之前写入内存,还是我错了?main() 不应打印任何小于 myalloc() 返回的地址的地址?!

期待您的回答,谢谢!

注意:这个例子是关于:内存应该写到哪里,而不是关于:myalloc() returns wrong memory....

(我对代码的改动:

  • 使用无符号代替 U32
  • 使用 myalloc() 而不是 allocateUnaligned()
  • C++ 转换而不是 C 风格)

最佳答案

代码已损坏。如果 malloc 会返回已经正确对齐的地址,比如 0 而你请求 8 字节对齐的地址,代码将返回地址 4,这显然是错误的。应删除以下行:

unsigned* ptrAdjustment = reinterpret_cast<unsigned*>( alignedAddress - 4 );

代码应该只返回 alignedAddress:

return reinterpret_cast<unsigned*>( alignedAddress );

(也应该是 void* 而不是 unsigned* 并且他应该使用 size_t 而不是 unsigned )。如果您希望代码返回原始的 malloc() 地址以防它已经正确对齐,您可以简单地将上面的行更改为:

return reinterpret_cast<void*>(misalignment?alignedAddress:rawAddress);

也很迂腐,函数中应该有断言来验证对齐是 2 的幂,例如assert((alignment&(alignment-1))==0);

关于c++ - 对齐内存分配器 : memory corruption (game engine architecture[Jason Gregory]),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24476294/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com