Search: Memory alignment, byte alignment, and struct alignment"
Example-01:
[Cpp]
# Include <stdio. h>
Typedef struct
{
Int;
Char B;
Int c;
} Test1;
Typedef struct
{
Char;
Int B;
Char c;
} Test2;
Typedef struct
{
Int;
Char B [9];
Int c;
} Test3;
Int main ()
{
Test1 t1;
Test2 t2;
Test3 t3;
Int;
Char B;
Char b2 [9];
Int c;
Printf ("Test1: % d \ n", sizeof (Test1 ));
Printf ("Test1: % d \ n", & t1 );
Printf ("Test1.a: % d \ n", & t1.a );
Printf ("Test1. B: % d \ n", & t1. B );
Printf ("Test1.c: % d \ n", & t1.c );
Printf ("Test2: % d \ n", sizeof (Test2 ));
Printf ("Test2: % d \ n", & t2 );
Printf ("Test2.a: % d \ n", & t2.a );
Printf ("Test2. B: % d \ n", & t2. B );
Printf ("Test2.c: % d \ n", & t2.c );
Printf ("Test3: % d \ n", sizeof (Test3 ));
Printf ("Test3: % d \ n", & t3 );
Printf ("Test3.a: % d \ n", & t3.a );
Printf ("Test3. B: % d \ n", t3. B );
Printf ("Test3.c: % d \ n", & t3.c );
Printf ("a: % d \ n", & );
Printf ("B: % d \ n", & B );
Printf ("b2: % d \ n", b2 );
Printf ("c: % d \ n", & c );
Return 0;
}
/*
VC +++ 6.0:
Test1: 12
Test 1: 1245044
Test1.a: 1245044
Test1. B: 1245048
Test1.c: 1245052
Test2: 12
Test 2: 1245032
Test 2.a: 1245032
Test2. B: 1245036
Test2.c: 1245040
Test3: 20
Test3: 1245012
Test3.a: 1245012
Test3. B: 1245016
Test3.c: 1245028
A: 1245008
B: 1245004
B2.: 1244992
C: 1244988
Gcc:
Test1: 12
Test 1: 2293572
Test1.a: 2293572
Test1. B: 2293576
Test1.c: 2293580
Test2: 12
Test 2: 2293560
Test 2.a: 2293560
Test2. B: 2293564
Test2.c: 2293568
Test3: 20
Test3: 2293540
Test3.a: 2293540
Test3. B: 2293544
Test3.c: 2293556
A: 2293536
B: 2293535
B2.: 2293526
C: 2293520
*/
The storage layout is as follows:
Example-02 (adapted from C traps and defects 4.4 ):
[Cpp]
# Include <stdio. h>
Int main ()
{
Int I;
Char c;
Int j;
Printf ("I address: % d \ n", & I );
Printf ("c address: % d \ n", & c );
Printf ("j address: % d \ n", & j );
For (I = 0; I <5; I ++)
{
Scanf ("% d", & c );
Printf ("% d", I );
}
Return 0;
}
/*
Gcc:
I address: 2293580
C address: 2293579
Jaddress: 2293572
3
0 3
0 3
0 3
0 100000
390
VC +++ 6.0:
I address: 1245052
C address: 1245048
Jaddress: 1245044
3
0 10000
1 3000
2 333333333333
3 333
4
*/
This program is okay when compiled and run with VC, but there is a problem when compiled and run with gcc, because the memory of the first three bytes of I is scanf () the last three bytes of the input integer are overwritten. The memory layout is shown in the figure below:
Example-01, Example-02 summary:
1. For the memory layout of the member variables in the struct, gcc and VC are the same (if gcc optimization is not taken into account). For the variables that are closely tied to the function, gcc is completed after the variable (low address), VC is completed before the variable (high address)