Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strange error during cast to __m128i

Tags:

c

sse

sse2

I'm trying to cast unsigned short array to __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];

First casting work fine, but the second one - not. I've got:

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

What's wrong? Can somebody help me?

like image 767
stack_user Avatar asked Jul 20 '12 01:07

stack_user


1 Answers

Watch your data alignment.

When you dereference a __m128i* or any other SSE type, the pointer is required to be aligned to 16 bytes. However, x and y are not guaranteed to be aligned to 16 bytes.

Enforcing alignment is dependent on the compiler.

Visual C++

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

GCC

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

Alternatively, you can use unaligned loads (abeit at a possible performance penalty):

__m128i n = __mm_loadu_si128((__m128i*) &y[0]);
__m128i m = __mm_loadu_si128((__m128i*) &x[0]);
like image 88
Mysticial Avatar answered Sep 18 '22 06:09

Mysticial