Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Struct varies in memory size?

Why is not 12 in the first case? Tested on: latest versions of gcc and clang, 64bit Linux

struct desc
{
    int** parts;
    int nr;
};

sizeof(desc); Output: 16

struct desc
{
    int** parts;
};

sizeof(desc); Output: 8

struct desc
{
    int nr;
};

sizeof(desc); Output: 4

like image 515
Blub Avatar asked Dec 27 '22 16:12

Blub


2 Answers

The compiler is allowed to add padding between struct members to make processing more efficient. This padding varies by platform, compiler version etc. It's one of the things that make sending structs over the network impossible.

You can use offsetof to find out where exactly your compiler is adding paddings.

like image 152
cnicutar Avatar answered Jan 11 '23 02:01

cnicutar


As the previous answer indicated, the compiler is allowed to add padding. This is usually done because sometimes the hardware requires that certain data types must occur on certain memory boundaries. It looks like your system wants to put pointers on an 8-byte boundary.

The padding is at the end of the structure and is necessary so that each element in an array of struct desc will still be on an 8-byte boundary.

like image 38
Dave Avatar answered Jan 11 '23 01:01

Dave