0

I want to test create NVMe I/O Submission Queue Invalid Queue Address Offset

I use C posix_memalign to alloc a memory range

But how to check that the address i get is QWord aligned?

I know if i want the address is word aligned then address end is 00h and double word aligned address end is 000h

So is qword aligned address end is 0000h?

Can i check by below?

if( address & 0xF != 0 )
    printf("Not qword aligned");

Thanks

JasonChiuCC
  • 111
  • 1
  • 6
  • By the way, `h` at the end usually means hex, or four bits per digit. The C way to specify a binary constant is `0b00`. Also one trailing binary zero means the word is aligned on a two-byte boundary, two trailing binary zeroes that it's aligned on a four-byte boundary, and four that it's aligned on a 16-byte boundary, which I think is what you probably mean? – Davislor Jul 09 '18 at 03:28
  • A bitwise operation on a pointer is not necessarily valid, bit converting `(uintptr_t)(void*)` will at least compile correctly.to an unsigned integral expression that can be used as the operand of `&`. – Davislor Jul 09 '18 at 04:33
  • an address terminating in `0000h` is 64Kb aligned.... I'm afraid. – Luis Colorado Jul 10 '18 at 19:55

1 Answers1

3

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.

However, this is an XY problem: posix_memalign() is defined to do what you want. Indeed, malloc() is guaranteed to return memory that meets the strictest alignment requirements of any type, and you can check 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.

Davislor
  • 14,674
  • 2
  • 34
  • 49