Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 303
Guillaume Paris Avatar asked Oct 02 '22 11:10

Guillaume Paris


2 Answers

#pragma pack(1)
struct _not_aligned {
  uint8_t a;
  uint32_t b; // unaligned 32-bit
};
#pragma pack()
like image 87
Jason Coco Avatar answered Oct 07 '22 06:10

Jason Coco


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.

like image 20
jalf Avatar answered Oct 07 '22 05:10

jalf