Linux中的结构分配在ARM中失败,但在x86中成功 [英] Structure assignment in Linux fails in ARM but succeeds in x86
问题描述
我注意到一些非常奇怪的事情. 说我已经定义了以下结构
I've noticed something really strange. say I've got the following structure defined
typedef struct
{
uint32_t a;
uint16_t b;
uint32_t c;
} foo;
此结构包含在我从网络接收到的大缓冲区中.
This structure is contained in a big buffer I receive from network.
以下代码在x86中有效,但在ARM上却收到SIGBUS
.
The following code works in x86, but I receive SIGBUS
on ARM.
extern void * buffer;
foo my_foo;
my_foo = (( foo * ) buffer)[0];
用memcpy替换取消引用的指针可以解决此问题.
在ARM中搜索SIGBUS后,我发现了这样一个事实,即它与内存对齐方式有关.
Searching about SIGBUS in ARM pointed me to the fact that this is related to memory alignment somwhow.
有人可以解释发生了什么事吗?
Can someone explain what's going on ?
推荐答案
您自己说过:特定处理器上存在内存对齐限制,并且buffer
对齐不正确,不允许从其中读取大于一个字节的内容.该任务可能被编译成三个较大实体的动作.
You said it yourself: there are memory alignment restrictions on your particular processor, and buffer
is not aligned right to permit reading larger than a byte from it. The assignment is probably compiled into three moves of larger entities.
对于memcpy()
,没有对齐限制,必须能够在任意两个地址之间进行复制,因此它可以执行实现该目标所需的一切.可能逐字节复制直到地址对齐为止,这是一种常见的模式.
With memcpy()
, there are no alignment restrictions, it has to be able to copy between any two addresses, so it does whatever is needed to implement that. Probably copying byte-by-byte until the addresses are aligned, that's a common pattern.
顺便说一句,我发现不用数组索引就能编写代码更加清晰:
As an aside, I find it clearer to write your code without array indexing:
extern const void *buffer;
const foo my_foo = *(const foo *) buffer;
这篇关于Linux中的结构分配在ARM中失败,但在x86中成功的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!