I’m currently writing a file loader for an ipad program and I’m getting strange EXC_BAD_ACCESS exceptions. Here is a short snipped of code that I think is the reason for the error:
float testFloat() {
char mem[32];
char *charPtr = &mem[0];
float *floatPtr = (float*)(charPtr + 1);
float f = *floatPtr; //EXC_BAD_ACCESS
return f;
}
The error happens only if the offset of charPtr is not divisible by 4, so I guess it could have something to do with pointer alignment on ARM CPUs.
You are correct, this is due to pointer alignment. On many RISC systems, the alignment needs to be at least as large as the data-type itself. (ARM falls into this category.)
In this case,
floatis 4 bytes, so the address needs to be aligned to 4 bytes. (divisible by 4)Furthermore, this type of type-punning violates strict-aliasing.On x86 systems, memory accesses do not always have to be aligned – but there will usually be a performance penalty on a misaligned access.