Linux 中的结构分配在 ARM 中失败,但在 x86 中成功 [英] Structure assignment in Linux fails in ARM but succeeds in x86

查看:17
本文介绍了Linux 中的结构分配在 ARM 中失败,但在 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屋!

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