Search code examples
c++gccalignmenticcvisual-studio

C++ memory alignment question


A line of code is worth a thousand words :) Here is my problem:

/* Platform specific 16-byte alignment macro switch.
   On Visual C++ it would substitute __declspec(align(16)).
   On GCC it substitutes __attribute__((aligned (16))).
*/
#define ALIGN_16 ...

struct ALIGN_16 A {...};

A* ptr = new A;
A* ptr2 = new A[20];

assert(size_t(ptr) % 16 == 0);

for (int i=0; i<20; ++i)
    assert(size_t(ptr2+i) % 16 == 0);

assert(sizeof(A) % 16 == 0);

Can I expect that all assertions pass on platforms with SSE support? Thank you.

EDIT. Partial answer. I did some test with VS2008, GCC and ICC. MS compiler did align both ptr and ptr2, but GCC and ICC failed to align ptr2.


Solution

  • Is there any guarantee of alignment of address return by C++'s new operation?

    In other words, you can use the standard to justify your assumption that it should work, but in practice, it may blow up in your face.

    Visual C++ 6 did not align doubles allocated via new properly, so there you go.