Strange error during cast to __m128i

I am trying to use unsigned short array for __m128i:

const unsigned short x[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
const unsigned short y[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};

__m128i n = *(__m128i*) &y[0];
__m128i m = *(__m128i*) &x[0];

The first casting works fine, and the second does not. I have:

Unhandled exception at 0x013839ee in sse2_test.exe: 0xC0000005: Access violation reading location 0xffffffff.

What happened? Can someone help me?

+5
source share
2 answers

Watch data alignment.

When dereferencing __m128i*or any other type of SSE, the pointer must be aligned with 16 bytes. However x, ythey cannot be aligned with 16 bytes.

Forced alignment is compiler dependent.

Visual C ++

__declspec(align(16)) const unsigned short x[] = ...

NKU

const unsigned short x[] __attribute__((aligned(16))) = ...

Alternatively, you can use unbalanced loads (reduce with a possible decrease in performance):

__m128i n = __mm_loadu_si128((__m128i*) &y[0]);
__m128i m = __mm_loadu_si128((__m128i*) &x[0]);
+11
source

, , . C11 _Alignas, C99 C89, .

, , , C99 union:

union combine {
  unsigned short x[sizeof(__m128i)/sizeof(unsigned short)];
  __m128i y;
}

union combine X = { .x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15} };

union . X.y, .

+1

All Articles