blackout blackout - 15 days ago 7
C++ Question

Declaring a union pointer with a pointer inside

I'm trying to learn SSE instructions and I aspire to multiply two matices. However, when I try to initialize one of them, the program crashes with an


Access violation when typing in location


Here's the code that throws the error:

typedef union{
__m128 vec;
float* afloat;
}u_float;

int main(){

__declspec(align(16)) u_float *mat1;

mat1 = (u_float*)malloc(sizeof(u_float)*4);
for(int i = 0; i < 4; i++)
mat1[i].afloat = (float*)malloc(sizeof(float)*4);

for(int i = 0; i < 4; i++)
for(int j = 0; i < 4; j++)
mat1[i].afloat[j] = 1; // Error.

return 0;}



  1. Why is it throwing that error?

  2. And which is the best way to resolve the problem?


Answer

This has nothing to do with unions. You have typo in your loop:

for(int i = 0; i < 4; i++)
    for(int j = 0; i < 4; j++) // <-- Here
            mat1[i].afloat[j] = 1;

Notice that the inner for loop loops while i is less than 4, not when j is less than 4, so this loops infinitely.

Comments