I need this flag so i can access my buffer.
char * buffer = malloc( sizeof(int) + N*sizeof(double) ); //contains integer and array of doubles
int* i = (int*)buffer; //first element is int
double* A = (double*)buffer + sizeof(int) //second elementi is my array
printf(“%d %2f”,i, ((double)A)[0] ); //I get an alignment error, cant see the reason why
Thank you
Maybe because your doubles are not aligned to 8 bytes because you put a 4 bytes int in front?
Yes this might be the problem, but if i use memcpy to parse my buffer everything works fine
int value;
memcpy(&value, buffer,sizeof(int) );
buffer + = sizeof(int);
double array[N];
memcpy(array,buffer, N*sizeof(double) );
pritnf(“%d %2f”,value, array[i]);
Any hints why this version works? Thnx anyways
Because “array” is an array of doubles which the compiler automatically aligned correctly.
It should be enough to add a padding int to your original sources to make the doubles 8 bytes aligned again. Look at the least significant 3 bits of address “A”.
On second sight, this code is incorrect as well:
double* A = (double*)buffer + sizeof(int);
Typecasts have a higher operator precedence than the plus operator. That added the size of 4 doubles to the buffer address.
The correct (but still misaligned) code would have been
double* A = (double*)(buffer + sizeof(int));
Thank you for your time,
I think i solved my problem using a union to alliagn all my values inside my buffer;
union{
int i;
double;
}U;
Now i can access my buffer using buffer+=sizeof(U); so everything is aligned
to sizeof(U) = sizeof(double) = 8
Everything seems ok.