EXC_BAD_ACCESS和char指针,用于浮点指针转换 [英] EXC_BAD_ACCESS and char pointer to float pointer cast

查看:49
本文介绍了EXC_BAD_ACCESS和char指针,用于浮点指针转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在为ipad程序编写文件加载器,并且遇到了奇怪的EXC_BAD_ACCESS异常.这是我认为是错误原因的一小段代码:

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;
}

仅当charPtr的偏移量不能被4整除时,才会发生错误,因此我猜想它可能与ARM CPU上的指针对齐有关.

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.

推荐答案

您是正确的,这是由于指针对齐引起的.在许多RISC系统上,对齐至少需要与数据类型本身一样大. (ARM属于此类.)

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.)

在这种情况下,float为4个字节,因此地址需要对齐为4个字节. (可被4整除)

In this case, float is 4 bytes, so the address needs to be aligned to 4 bytes. (divisible by 4)

此外,这种类型的对等违反了严格的混叠.

在x86系统上,内存访问不一定总是必须对齐-但是通常会因未对齐的访问而降低性能.

On x86 systems, memory accesses do not always have to be aligned - but there will usually be a performance penalty on a misaligned access.

这篇关于EXC_BAD_ACCESS和char指针,用于浮点指针转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆