EXC_BAD_ACCESS and char pointer to a floating pointer

I am currently writing a file downloader for ipad and I am getting weird EXC_BAD_ACCESS exceptions. Here is a short code which, in my opinion, is the cause of 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 only occurs if the charPtr offset is not divisible by 4, so I assume this may be related to pointer alignment on ARM processors.

+3
source share
3 answers

You are right, this is due to alignment of the pointer. In many RISC systems, alignment should be at least the same as the data type itself. (ARM falls into this category.)

In this case float, 4 bytes, so the address must be aligned with 4 bytes. (divided by 4)

, punning .

x86 - ​​ .

+7

- . .

, http://www.cocos2d-x.org/forums/6/topics/18183

float *floatPtr = (float*)(charPtr + 1);
float f = *floatPtr; //EXC_BAD_ACCESS
return f;

float f;
unsigned char* pData = (charPtr + 1);
memcpy( &f, pData, sizeof( float ) );
+2

What about

struct MyStruct
{
char* _charPtr;
float* _floatPtr;
};

MyStruct myStruct = &mem[0];

float f = *(myStruct._floatPtr);

Will this violate the requirement of alignment of the pointer?
Not sure, but worth a try.

-1
source

All Articles