The results of data type placement in struct and class defined.
I recently toke a class on computer architecture and was amazed at how many bytes I could save by observing
good memory alignment during the placement of variables in structs and classes.
For example, the Windows O.S. is different from Linux in the fact that memory alignment follows a +8 byte cell padding convention. Whereas in Linux that padding is only +4 bytes.
CODE
// Example 1:
struct first
{
float x[2];
int I[2];
char c;
} *ptr;
Has an alignment of...
Bytes:.....0...........4.........8........12......16.17.......20
Windows: |_ x [1]_|_x[2]_|_i[1]_|_i[2]_|_c|////////|
.....Linux: |_ x [1]_|_x[2]_|_i[1]_|_i[2]_|_c|////////|
Notice the char c. Due to alignment conventions both systems allocate an extra 3 bytes for the struct.
Here is a more stunning example...
CODE
// Example 2:
struct bad
{
double v;
char c1;
char c2;
int num;
} *ptr;
Has an alignment of...
Bytes:.....0..........4..........8.......10.....12.....16..........20.........24
Windows: |______v______|c1|c2|////////////|_____i__|/////////|
.....Linux: |______v______|c1|c2|////|___i__|
In Windows 10 bytes of memory are wasted because of the padding convention. The chars are a single byte each
and then they must be padded 6 bytes over to make a total of +8 bytes.
Linux only wasted 2 bytes.
So let's apply what we know about proper alignment and look at the difference.
CODE
// Example 3
struct good // Upgrade
{
char c1;
char c2;
int num;
double dub;
} *ptr;
Has an alignment of...
Bytes:......0.......2 .....4....6.....8........................16
Windows: |c1|c2|__num__|////|_____ dub _____|
.....Linux: |c1|c2|__num__|////|_____ dub _____|
The difference is very noticeable. Proper alignment saved 8 bytes in Windows. Linux remains unchanged.
Conclusion: This technique is a good practice for the C/C++ programmer and can also be applied to other programming languages. It is not difficult to do and is a great way to make a more efficient, less memory allocated program. Surprisingly it increases the security of the program. What if the user just entered their credit card number. That 16 bit 4 byte number could still be in RAM and even protected by poor alignment! This sounds like an extreme case but it is possible. As a programmer you wouldn’t want to be responsible for that kind of a security leak. So take charge by observing the art of variables placement!
This post has been edited by trixt.er: 7 Sep, 2009 - 08:24 PM