Question about struct sizes

Hi all,

Basically been writing some code and I came across a funky error when reading a a file and was off by one with my struct definition.

This was the original code:

1
2
3
4
5
struct lumpinfo_t {
    int filepos;
    int size;
    char name[9]; // meant to be 8
};


So I decided to test the size of the struct and it turned out to be 20 bytes. When I noticed my error I changed 9 to 8 and the size jumped down to 16.

If I was to guess, modern computers don't used 1 byte chunks any more as most int's are at least 4 bytes so instead of creating a struct of size 17 bytes it pads the struct by 3 extra bytes.

If I'm wrong feel free to correct me but my basic question is why padding does this? Is it an optimisation or something?
Last edited on
It's padding to make sure the types are align correctly. A primitive type that is 4 bytes is normally stored on a memory address that is divisible by 4. How important this is depends on the hardware. Some hardware can't handle unaligned data at all, some are just slower.

In your case 3 bytes of padding is added to make sure the ints are aligned properly if you were to store them in an array.

| int filepos   | int size      | char name[9]                      | padding   |
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |10 |11 |12 |13 |14 |15 |16 |17 |18 |19 |
---------------------------------------------------------------------------------
| int filepos   | int size      | char name[9]                      | padding   |
|20 |21 |22 |23 |24 |25 |26 |27 |28 |29 |30 |31 |32 |33 |34 |35 |36 |37 |38 |39 |
---------------------------------------------------------------------------------
| int filepos   | int size      | char name[9]                      | padding   |
|40 |41 |42 |43 |44 |45 |46 |47 |48 |49 |50 |51 |52 |53 |54 |55 |56 |57 |58 |59 |


If there was no padding the ints for some of the elements would not get aligned correctly.

| int filepos   | int size      | char name[9]                      |
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |10 |11 |12 |13 |14 |15 |16 |
---------------------------------------------------------------------
| int filepos   | int size      | char name[9]                      |
|17 |18 |19 |20 |21 |22 |23 |24 |25 |26 |27 |28 |29 |30 |31 |32 |33 |
---------------------------------------------------------------------
| int filepos   | int size      | char name[9]                      |
|34 |35 |36 |37 |38 |39 |40 |41 |42 |43 |44 |45 |46 |47 |48 |49 |50 |
Last edited on
Topic archived. No new replies allowed.