Q67.Marks: +2.0UGC NET Paper 2: Computer Science 2020
Suppose you are compiling on a machine with 1-byte chars, 2-byte shorts, 4-byte ints, and 8-byte doubles, and with alignment rules that require the address of every primitive data element to be an integer multiple of the element's size. Suppose further that the compiler is not permitted to reorder fields: padding is used to ensure alignment. How much space will be consumed by the following array?
struct {
short s;
char c;
short t;
char d;
double r;
int i;
} A[10]; /*10-element array of structs*/
1.150 bytes
2.320 bytes
3.240 bytes✓ Correct
4.200 bytes
Solution
The correct answer is option 3.
Key Points
"alignment rules" that "require the address of every primitive data element to be an even multiple of the element’s size". It's not very interesting that we're talking about alignment rules; we knew that already.
"require the address" of "every primitive data element" to be "an even multiple of the element’s size". Now we're getting somewhere. We have a requirement and a scope:
Requirement: The address is an even multiple of the element's size.
Scope: Every primitive data element.
So, every time we position an element, we must impose the requirement. It may also mean "even" as in "integral" rather than "multiple of two"
That would make the array:
Offset
Variable
Size
Range
0
s
2
0-1
4
c
1
2-2
8
t
2
4-5
12
d
1
6-6
16
r
8
8-15
24
i
4
16-19
28
*
4
20-23
32
s
2
24-25
34
c
1
26-26
36
t
2
28-29
38
d
1
30-30
48
r
8
32-39
56
i
4
40-43
60
*
4
44-47
In that case, you have 24 bytes per element for a total of 240 bytes. Again, you need padding to ensure that r is aligned correctly.