[英]How to check the malloc address is QWord aligned?
I want to test create NVMe I/O Submission Queue Invalid Queue Address Offset 我要测试创建NVMe I / O提交队列无效的队列地址偏移量
I use C posix_memalign to alloc a memory range 我使用C posix_memalign分配内存范围
But how to check that the address i get is QWord aligned? 但是,如何检查我得到的地址是否与QWord对齐?
I know if i want the address is word aligned then address end is 00h and double word aligned address end is 000h 我知道我是否要地址按字对齐然后地址结尾为00h和双字对齐地址结尾为000h
So is qword aligned address end is 0000h? 那么qword对齐的地址结尾是0000h吗?
Can i check by below? 我可以在下面检查吗?
if( address & 0xF != 0 )
printf("Not qword aligned");
Thanks 谢谢
A simple way is to test the low bits with a bitwise and. 一种简单的方法是按位与进行测试低位。 There isn't a perfectly-portable way of doing that with no implementation-defined behavior, but that doesn't matter because you're targeting one specific architecture. 没有实现定义的行为,没有一种完美的便携式方法,但这没关系,因为您的目标是一个特定的体系结构。 So, you can test that p
is aligned on a 16-byte boundary, on any C compiler for the x86, with (uintptr_t)(void*)p & 0x0f == 0
. 因此,可以在(uintptr_t)(void*)p & 0x0f == 0
,在x86的任何C编译器上测试p
是否在16字节边界上对齐。
However, this is an XY problem: posix_memalign()
is defined to do what you want. 但是,这是一个XY问题: posix_memalign()
被定义为执行所需的操作。 Indeed, malloc()
is guaranteed to return memory that meets the strictest alignment requirements of any type, and you can check alignof(max_align_t)
. 实际上,保证malloc()
返回满足任何类型的最严格对齐要求的内存,并且您可以检查alignof(max_align_t)
。
In this case, you might want to use aligned_alloc()
, which exists in the standard library to allocate memory with a stricter alignment requirement, and has a simpler interface, or calloc()
, which allows you to specify the element size and also zeroes out the memory. 在这种情况下,您可能想使用标准库中存在的aligned_alloc()
来分配具有更严格对齐要求的内存,并且具有一个更简单的接口或calloc()
,该接口允许您指定元素大小并且也可以为零内存不足。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.