View Single Post
Posts: 503 | Thanked: 267 times | Joined on Jul 2006 @ Helsinki
#12
Originally Posted by mlvj
If you tell me the compiler directives to force stuff to be aligned, I'll try adding them in to (hopefully) the appropriate places.
All the stuff should be already properly aligned by the compiler. But you can get into a trouble if using pointers conversion though, such as '*(int *)(buffer + 1)' in the example below. Modern compilers can warn about suspicious pointers conversion with -Wall option. Also beware of packed structs on ARM, there are two pitfalls: first is the alignment of data members, the second is the size of struct itself.

Here is the example of code you can experiment with to see these pitfalls:

Code:
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>

#pragma pack(1)
typedef struct s
{
    char x;
    int y;
} S;
#pragma pack()

int main()
{
    int i;
    char *buffer = (char *)malloc(16);
    for (i = 0; i < 16; i++) buffer[i] = i;

    printf("reading unaligned value from the buffer at offset 1: %08X\n", 
        *(int *)(buffer + 1));
    printf("offsetof(S, y)=%d\n", offsetof(S, y));
    printf("sizeof(S)=%d\n", sizeof(S));

    free(buffer);
    return 0;
}
On x86 it prints:
Code:
reading unaligned value from the buffer at offset 1: 04030201
offsetof(S, y)=1
sizeof(S)=5
On arm (and also when run with qemu) the results will be different.