Memory Alignment
Created Thursday 05 May 2016
Consider the following struct:
1 struct S
2 {
3 short s1;
4 char b1[3];
5 float f;
6 char b2[3];
7 double d;
8 short s2;
9 }
Steps to figure out the memory for the struct:
- What is the largest data type in terms of memory? (In this case, a double, with size of 8 bytes)
- Make sure that every element does not "intersect" a place which is a multiple of 8 starting from the starting location.
For the above example:
| Variable | Size (Bytes) |
|---|---|
| s1 | 2 |
| b1 | 3 |
| padding | 3 |
| f | 4 |
| b2 | 3 |
| padding | 1 |
| d | 8 |
| s2 | 2 |
| padding | 6 |
REMEMBER: The end needs padding too, if it isn't large enough to rule of filling up to the multiple of the largest data type's size!
Backlinks: index:CS225 Notes:Topics