Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
322 views
in Technique[技术] by (71.8m points)

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

The following code works in x86, but I receive SIGBUS on ARM.

extern void * buffer;
foo my_foo;
my_foo = (( foo * ) buffer)[0];

replacing the pointer dereferencing with memcpy solved the issue.

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...