请考虑以下Objective-C++ iPhone应用程序(TestMemAppDelegate.mm)。它在iPhone上使用EXC_BAD_ACCESS(iOS 4.0的3GS)崩溃。它在模拟器中工作正常。这显然是一个内存对齐的事情,因为如果“DataA”结构在8字节边界上启动,它可以在iPhone上正常工作。非8字节对齐的内存访问会导致iOS 4.0的iPhone 3GS上的内存访问冲突
任何人都可以解释原因吗?这是ARM架构的东西吗? ARM编译器?
@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
谢谢。基于你的回答,我在文档中找到了它:http://www.keil.com/support/man/docs/ca/ca_ap_byte_alignment.htm – 2010-08-09 13:44:49