Programming 7 — What does “unaligned access” mean, and how can I fix it?
Unaligned accesses typically come up when programs use malloc(3) or other memory allocation routines in atypical ways, or when programs do certain (hazardous) kinds of type casts. malloc(3) returns data aligned to the most restrictive alignment (8 byte boundaries). If you are writing your own malloc wrapper (say to add a reference count) and you write code like this: char *mymalloc(int size) { short *newmem; newmem = (short *) malloc(size + sizeof(short)); *newmem = 1; /* initialize reference count */ return (char *) (newmem + 1); } you are then returning a pointer that is no longer 8-byte aligned. Now, code like: int *i; i = (int *) mymalloc(sizeof(int)); *i = 10; will generate unaligned access messages whenever *i is used. An example of dangerous casting would be something like: char buffer[100]; int i; i = (int)*((int *)&buffer[3]); The program will usually still run correctly, because an exception handler in the kernel performs an unaligned read. There are some rare cases, howe