Structure assignment in Linux fails in ARM but succeeds in x86

后端 未结 4 1602
深忆病人
深忆病人 2020-12-06 21:25

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;
         


        
4条回答
  •  余生分开走
    2020-12-06 22:00

    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;
    

提交回复
热议问题