Structure/Class Padding
Structure Padding: Whenever we create classes and structures we should pay special attention to the way we r defining variables insdie, because the size of the struct or class depends on it. Also frequently used variables shoild be kept on top in order to avoid cache misses. A class or a struct is always a multiple of the largest sized datatype inside it. for eg: struct A { double a; char ch; }; now sizeof(A) == 16 and not 8 + 1 = 9 even if the struct is rewritten like struct A { double a; char ch; char ch1; char ch2; char ch3; }; even then the size vil be 16 All variables defined inside a struct or a class are alligned in memory according to their size. Like an int can only be stored at addresses 4,8 and 12 that are multiples of 4. 6 is an invalid address for an int.Similarly for double it can be strored only at multiples of 8. NOTE: A char can be stored at any byte coz its nly of 1 byte. for eg: struct A { char ch; int x; char ch1; double d; }; 1 + 4 + 1 + 8 = 14 and considering double final size must be 16 but actually sizeof(A) == 24 .............WHY??? Now lets see WHY, hypothetical starting address 0; 0-1 1 byte for ch now next valid address for int is 4, hence 1-2 padding 2-3 padding 3-4 padding 4-8 4 bytes for int 8-9 1 byte for ch1 Now next valid address for double vil be 16, hence 9-16 7 bytes for padding 16-24 8 bytes for d So we wasted 10 bytes in padding dats actually a quite if you use dis struct for creating a 2D array of size 100*100 total objects of struct = 10000 bytes wasted on padding = 10000* 10 bytes Approx 98 kB is being wasted on just padding. Lets rearrange d structrure now struct A { double d; int x; char ch; char ch1; }; 0-8 8 bytes for double 8-12 4 bytes for int 12-13 1 byte for ch 13-14 1 byte for ch1 since d structure needs to be a multiple of 8 so final size would be 16 Only 2 bytes required for padding So for 100*100 array only 19kB is wasted on padding Simply shuffling d variables inside saved us 78kB So always keep this thing in mind while creating classes and structure in the future.















