Data Alignment

From PortaWiki

Jump to: navigation, search

Certain CPUs have strict requirements or performance penalties relating to the address you access data on. For example, UltraSparc CPUs have a teary if you try to access an integer that isn't on a 4 byte boundary. This quirk leads to some interesting issues when you try to port code between various platforms.

(this is an extract from MySQL Bug 10948

This simple C program:

#include <stdio.h>

struct a {
   void *a;
   unsigned long long b[1];
};

int main()
{
  printf("%u\n",sizeof(struct a));
}

Will output 16 on PPC and 12 on x86. On PPC32 we are getting things aligned to 64bits (possibly due to the 64bit sized member, i'm not sure).

See http://www-128.ibm.com/developerworks/power/library/pa-dalign/ for an explanation of PPC alignment issues.

so a malloc(sizeof(void*)+extra_bits) is wrong. with a malloc(sizeof(struct a)+N) you wast sizeof(long long), but it's better than crashing or, you can do malloc(sizeof(struct a)-sizeof(long long)+N)

The GCC flag -Wpadded would have generated a warning for this. It is possible that it could be a good idea to enable this warning.

Personal tools