There are cases when a 32-bit variable cannot be correctly aligned

The following link: http://msdn.microsoft.com/en-us/library/ms684122 (VS.85) .aspx , states that "simple reads and writes to correctly aligned 32-bit variables are atomic operations." I am wondering if in a C ++ program all 32-bit variables are correctly aligned by default correctly. In other words, there is a case when a 32-bit variable cannot be correctly aligned.

+5
c ++ memory-alignment
source share
2 answers

Unless you tell the compiler to do otherwise, it will correctly align 32-bit variables.

You can write code that puts 32-bit variables into unaligned addresses (for example, by creating a char array and writing your int to an odd index in the array).

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

But if you do not, your variables will be correctly aligned.

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

All Articles