Misaligned structure fields, works regardless... Structure packing?
2005-12-22 by Thiadmer Riemersma (ITB CompuPhase)
Hello everyone, I just saw that I have a couple of structure fields that are not well aligned. That is, a 4-byte pointer starts at an odd memory address (instead of at a multiple of 4). The funny thing is, the code runs fine. What's up? is GNU GCC too smart? Is this a side-effect of packing? Some background: I have had a couple of nasty bugs in the firmware that turned out to be caused by mis-alignment. When another nasty bug came up earlier this week, I thought "alignment" again, and set out (finally) to write that utility that helps me find misaligned variables, structure fields, etc. This time, the nasty bug turned out to be a stack overrun, but I made the utility regardless and ran it on the code. I found that in a few instances, structures could start at an odd address, even though the first element is a pointer. This is what all mis-aligned structures have in common: - their first element is a pointer to char - all members have __attribute((packed)) - the structure itself has __attribute((packed)) too Other observations: - both structures in RAM and in ROM can be mis-aligned - both global and "static local" variables can be mis-aligned My guess is that the first member being a pointer to char is just coincidence. So probably this has to do with structure packing. This implies that GCC must have an alternative method to access the mis-aligned structure fields, and in fact, it means that GCC must use this alternative (and probably slower) access method for all accesses to packed structures. Can anyone confirm/refute this? Kind regards, Thiadmer