非8字节对齐的内存访问会导致内存访问冲突在iPhone 3GS与iOS 4.0 [英] Non 8 Byte aligned memory access causes memory access violation on iPhone 3GS with iOS 4.0
问题描述
考虑下面的Objective-C ++的iPhone程序(TestMemAppDelegate.mm)。它崩溃与iPhone(3GS与iOS 4.0)的EXC_BAD_ACCESS。它在模拟器工作正常。这显然是一个内存对齐的东西,因为它适用于iPhone的罚款,如果在数据A结构上的8字节边界开始。
任何人能解释的原因是什么?它说的是与ARM架构? ARM编译器?
@implementation TestMemAppDelegate
typedef结构数据A
{
浮X;
unsigned char型ÿ;
};
- (BOOL)应用:(*的UIApplication)的应用didFinishLaunchingWithOptions:(NSDictionary的*)launchOptions { 字符* MEM1 =(字符*)malloc的(4096); 数据A * PTRA =(数据A *)(MEM1 + 1); //这里我们却将对齐
ptrA-> X = 10.0f;
的printf(A:%.2f \\ n,ptrA-> X); //这崩溃 //视图控制器的视图添加到窗口和显示。
[窗口addSubview:viewController.view];
[窗口makeKeyAndVisible] 返回YES;
}
@结束
是的,它是一个定位的问题。一个浮点必须是4字节对齐。英特尔的x86处理器允许未对齐访问(但性能损失)。在ARM这是不允许的,产生你看到错误。
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
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.
这篇关于非8字节对齐的内存访问会导致内存访问冲突在iPhone 3GS与iOS 4.0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!