3

I am using gcc 4.9.2 and I am trying to properly align statically initialized arrays for use with AVX. Here is the gist of the code that segfaults due to alignment issues:

#include <iostream>
#include <cstddef>

struct B {
    alignas(32) double x[1] = {0};
};

struct A
{
    A() { b1 = new B(); b2 = new B(); }

    B* b1;
    B* b2;
};

int main(int argc, char** argv) {
    A a;

    int ret = (ptrdiff_t) a.b1->x % 32 + (ptrdiff_t) a.b2->x % 32;

    std::cout << (ptrdiff_t) a.b1->x % 32 << "," << (ptrdiff_t) a.b2->x % 32 << "\n";

    return ret;
}

On my system, array a.b2->x is not aligned on a 32 byte boundary. The size of x does not matter, as long as x is an array (so "double x = 0" works fine). If I make the pointers to B statically allocated members instead, it works properly. If I create local variables *b1 and *b2 inside main, it works properly. If I use dynamically allocated arrays inside class A and posix_memalign, it works properly.

Am I misunderstanding something about alignas.

max66
  • 65,235
  • 10
  • 71
  • 111
kounoupis
  • 329
  • 1
  • 10

1 Answers1

1

If I understand correctly, from the following document

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3396.htm

new it's not required to respect the alignas.

max66
  • 65,235
  • 10
  • 71
  • 111
  • Note, you can implement a custom `operator new` that calls `posix_memalign`. – o11c Apr 08 '16 at 22:26
  • I also posted a bug in gcc-bugzilla and got a similar answer: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=70603 – kounoupis Apr 09 '16 at 12:17