I would like to allocate some char buffers0, to be passed to an external non-C++ function, that have a specific alignment requirement.
The requirement is that the buffer be aligned to a N-byte1 boundary, but not to a 2N boundary. For example, if N is 64, then an the pointer to this buffer p should satisfy ((uintptr_t)p) % 64 == 0 and ((uintptr_t)p) % 128 != 0 - at least on platforms where pointers have the usual interpretation as a plain address when cast to uintptr_t.
Is there a reasonable way to do this with the standard facilities of C++11?
If not, is there is a reasonable way to do this outside the standard facilities2 which works in practice for modern compilers and platforms?
The buffer will be passed to an outside routine (adhering to the C ABI but written in asm). The required alignment will usually be greater than 16, but less than 8192.
Over-allocation or any other minor wasted-resource issues are totally fine. I'm more interested in correctness and portability than wasting a few bytes or milliseconds.
Something that works on both the heap and stack is ideal, but anything that works on either is still pretty good (with a preference towards heap allocation).
0 This could be with operator new[] or malloc or perhaps some other method that is alignment-aware: whatever makes sense.
1 As usual, N is a power of two.
2 Yes, I understand an answer of this type causes language-lawyers to become apoplectic, so if that's you just ignore this part.
pcome in to this? Are you talking aboutpas in a pointer to the byte buffer?pis a pointer the byte buffer (which is why I called itp). I was slightly cagey in the actual question by callingpan "address" rather than a pointer, because if I called it a pointer a bunch of lawyers would jump down my throat pointing out that arithmetic cannot be done directly on pointers, and going on about the platform-specifics ofintptr_t, etc.x86andarmtags since those are the platforms I'm most interested in, so if there is a solution of the "not standard, but works in practice variety" I want it to at least work there. I don't think the question is vague because I'm at least asking if there is a standard way to do this, and the "as a practical matter, this works..." part is usually just implied. I shouldn't be punished for mentioning it explicitly.(p % 64 == 0) && (p % 128 != 0)is most peculiar. May I ask where this does come from? In particular the second condition is very odd.