- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我刚刚在读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()
最佳答案
代码已损坏。如果 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/
我正在尝试使用多线程并指定要使用的线程数来实现 Java 中的 Gregory-Leibniz。我失败了,因为最后 PI 给我的值为 43。 有人可以帮我吗?如果我不必输入线程数我会很好,但是输入线程
我正在阅读Dagger2的源代码,在ScopedProvider中有静态字段UNINITIALIZED这表明 instance字段尚未初始化。我已经阅读并理解了双重检查惰性初始化习惯用法,但为什么有必
我必须使用格雷戈里-莱布尼茨级数计算 Pi 的值: pi = 4 * ((1/1 - 1/3) + (1/5 - 1/7) + (1/9 - 1/11) + ...) 我想用 JavaScript 编
我刚刚在读Game Engine Architecture by Jason Gregory S.212,当我偶然发现他分配对齐内存的代码时。我认为他正在产生内存损坏并使用以下代码自行尝试: void
我已经找到了“The Coder's Apprentice Learning Programming with Python 3”练习 8.3 的解决方案,它与作者的解决方案略有不同。我想在这里问一下
我是一名优秀的程序员,十分优秀!