Mircea Ionica
Mircea Ionica

Reputation: 87

Alignment considerations when I treat a memory area as an array of structs

Let's consider that I have defined a memory area like (Note: uint8 means unsigned char):

uint8 myMemoryArea[1024];

And I have a struct like:

typedef struct
{
   uint8 * ptrToMyVar; 
   uint8 otherVar;
} myStruct_type;

I want to consider myMemoryArea as being an array of myStruct_type, so I would want to perform a random access to the memory area like, for example:

myStruct_type * myPtrToStruct = (* myStruct_type)(&(myMemoryArea[ELEMENT_TO_ACCESS * sizeof(myStruct_type)]));
myPtrToStruct->otherVar =  2;

Is this machine independent code? Should I expect troubles with alignment or padding? I guess padding is OK here as long as I use sizeof.

Should I ensure that myMemoryArea starts from an address divisible by sizeof(* char) - perhaps defining it as an array of pointers ?

Upvotes: 3

Views: 371

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 753465

There's no guarantee that myMemoryArea will be appropriately aligned. Depending on your CPU and O/S and compiler, you may get crashes or very slow access to misaligned data. (See also: Solve the memory alignment in C interview question that stumped me).

Consider what happens if your variable is declared in this context:

double d1;
uint8  c1;
uint8  myMemoryArea[1024];
uint8  c2;
douebl d2;

There's every reason to expect d1 to be properly aligned; the compiler will be failing you horribly if it is not. There's no reason to expect any unusual treatment for c1; a single byte can be stored on any alignment. The myMemoryArea data also does not have to be aligned specially; there might be no space around it, and it may well be at an odd address. The c2 variable doesn't need special treatment; d2 will be properly aligned (and there's likely to be 6 bytes unused space in the data.

If myMemoryArea is on an odd-byte alignment, and you use a RISC machine to access the memory structure, you will most likely get a SIGBUS error. On an Intel machine, you may get very slow access instead.

Upvotes: 2

Related Questions