2

I've made a doubly linked structure in C, and need to know how to calculate the size of custom made structures. I understand the size of certain data types, and that pointers are 8 bytes on my machine.

However when I create this data type

struct doublylinked {
    int data;
    struct doublylinked *next;
    struct doublylinked *prev;
};

I get that all the values inside add up to 20 bytes in total.

size of data = 4

size of next = 8

size of prev = 8

However when I print out the size of this data type it equals 24.

size of doublylinked = 24

Where are these extra 4 bytes coming from?

Thanks

Jaeren Coathup
  • 377
  • 5
  • 16

2 Answers2

3

The extra space come from the padding added by the compiler, which make access faster on some CPU.

It might actually look like this in memory:

data     [4 bytes]
padding  [4 bytes] <- That way, next is aligned on a multiple of his own size
next     [8 bytes]
prev     [8 bytes]
toasted_flakes
  • 2,502
  • 1
  • 23
  • 38
0

The 8-byte next and prev variables need to have an 8-byte alignment.

In other words, they need to be located in memory addresses divisible by 8.

So the compiler adds a 4-byte padding before or after the 4-byte data variable.

Please note that this is generally platform-dependent (i.e., some processors may support unaligned load/store operations, in which case, the compiler may choose to avoid the padding).

barak manos
  • 29,648
  • 10
  • 62
  • 114