Structure assignment in Linux fails in ARM but succeeds in x86

依然范特西╮ 提交于 2019-12-01 09:08:09

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;

C Standard [ISO/IEC 9899:2011] - 6.3.2.3, paragraph 7:

A pointer to an object or incomplete type may be converted to a pointer to a different object or incomplete type. If the resulting pointer is not correctly aligned for the pointed-to type, the behavior is undefined.

Source: CERT Secure Coding Standards

ARM-based systems expect structures to be aligned on a word boundary. If it is not the case you can have different behaviours (in the linux kernel for instance, these behaviours are described in /proc/cpu/alignement and one of them is to send a SIGBUS).

What you did with memcpy() is that you have forced the data structure alignment.

i was developing some download application on freescale imx a while back....had a memory alignment problem there(requirement was that executable be in multiple of 512 bytes)...Fundamental difference between arm and x86...But the thing to remember with memcpy is that it does a byte by byte copy ...So, it might work but please be sure to check for run-time problems...Donot be fooled by memcpy...Always a good idea to have a memory aligned structure for your specific platform.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!