Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Size of struct that contains two pointers

Tags:

c

struct

size

What is the size of this struct? (32 bit system calculation. Not 64 bit.)

struct list_element
{
  short data;
  struct list_element* next;
  struct list_element* prev;
};

I have tried calculating the size with these formulas:

  1. (sizeof(list_element*) + sizeof(short)) + ((sizeof(list_element*) * 2)

    • (4 + 2) + (4 * 2) = 6 + 8 = 14
  2. (sizeof(short)) + (sizeof(list_element*) * 2)

    • 2 + (4 * 2) = 2 + 8 = 10
  3. (sizeof(list_element*) + sizeof(list_element*) + sizeof(short)) + (sizeof(list_element*) * 2)

    • (4 + 4 + 2) + (4 * 2) = 10 + 8 = 18
  4. (sizeof(list_element*) + sizeof(list_element*) + sizeof(short))

    • (4 + 4 + 2) = 10

However, they do not return the correct answer. What formula do you use to calculate the size of this struct?

Update:

My teacher says we a re ignoring data alignment... Hopefully that does not throw anyone off too much since you are used handling data alignment with your code and structs...

Update 2 Thank you for the help and the introduction to data alignment.

The answer was 10 without data alignment... Not sure why I am in such a rush to work with data alignment in C... Is it fun?

Also, the answer with data alignment is 12. As you guys explained, you have to data align the short to match the integers. Therefore, you have (2 + (2 additional bytes)) + 4 + 4 = 12.

like image 983
Programmer MJM Avatar asked Dec 25 '22 03:12

Programmer MJM


1 Answers

The size of the struct is given by:

size_t size = sizeof(struct list_element);

The fact that you have two members that are pointers to the struct just means you are adding the size of a pointer, twice. On a 32 bit build, sizeof would resolve to an additional 4 bytes per pointer, on a 64 bit build, it would result in an additional 8 bytes per pointer.

Another thing to be aware of is that the size of your struct is likely not simply the sum of the sizeof's of the individual members, as storage in a struct is often padded for alignment purposes. So, between your short, and the next member, the padding will result in additional size.

The reason I used the word likely is that if a pragma pack directive was used in your source, the packing alignment could be changed, resulting in a different value for sizeof.

Two good discussions on struct alignment padding: A general discussion here, and How to reduce memory footprint here. The second link is particularly interesting as it deals with structure alignment, padding and bit fields, and how each can affect memory usage.

like image 193
ryyker Avatar answered Jan 06 '23 03:01

ryyker