Is there cases where a 32-bit variable could not been properly-aligned

纵饮孤独 提交于 2019-12-07 05:06:27

问题


In the following link: http://msdn.microsoft.com/en-us/library/ms684122(VS.85).aspx, it is said that "Simple reads and writes to properly-aligned 32-bit variables are atomic operations". I'm wondering if in a c++ program all 32-bit variables are by default properly-aligned. Saying differently is there any case where a 32-bit variable could not been properly-aligned.


回答1:


If you don't tell the compiler to do otherwise, then it will align 32-bit variables correctly.

You can write code which places 32-bit variables at non-aligned addresses (for example by creating an array of char, and writing your int to an odd index in the array).

You can also use compiler #pragmas to tell the compiler not to align specific types or variables.

But if you don't do any of that, then your variables will be aligned properly.




回答2:


#pragma pack(1)
struct _not_aligned {
  uint8_t a;
  uint32_t b; // unaligned 32-bit
};
#pragma pack()


来源:https://stackoverflow.com/questions/22037332/is-there-cases-where-a-32-bit-variable-could-not-been-properly-aligned

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