Search code examples
iphonememorymallocarmobjective-c++

Non 8 Byte aligned memory access causes memory access violation on iPhone 3GS with iOS 4.0


consider the following Objective-C++ iPhone Application (TestMemAppDelegate.mm). It crashes with an EXC_BAD_ACCESS on the iPhone (3GS with iOS 4.0). It works fine in the Simulator. It is clearly a memory alignment thing, because it works fine on the iPhone if the "DataA" struct starts on a 8 Byte border.

Can anyone explain the cause? Is it something with the ARM architecture? ARM compiler?

@implementation TestMemAppDelegate


typedef struct DataA
{
 float    x;
 unsigned char  y;
};


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    

 char* mem1 = (char*)malloc(4096);

 DataA* ptrA = (DataA*)(mem1 + 1); // Here we shift the alignment
 ptrA->x = 10.0f;
 printf("A: %.2f\n", ptrA->x); // Here it crashes



    // Add the view controller's view to the window and display.
    [window addSubview:viewController.view];
    [window makeKeyAndVisible];

    return YES;
}


@end

Solution

  • Yes it's an alignment issue. A float needs to be 4-byte aligned. An Intel x86 CPU allows mis-aligned access (but at a performance penalty). On ARM it is not allowed and generates the error you see.