Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is offsetof(member) equal to sizeof(struct)?

I have a struct defined as:

struct smth
{
    char a;
    int b[];
};

When I call sizeof and offsetof on this struct:

cout << sizeof(struct smth) << endl;
cout << offsetof(struct smth, b) << endl;

Output is:

4
4

How come when the size of the stuct is 4 and char is using 1 byte, the offset of the int array is 4? Why is there some kind of padding? Also, why isn't the int array occupying any space at all?

like image 903
bugra Avatar asked Aug 17 '13 15:08

bugra


3 Answers

How come when the size of the stuct is 4 and char is using 1 byte, the offset of the int array is 4? Why is there some kind of padding?

There is padding because the C standard allows it; the compiler often aligns variables to improve performance.

Also, why isn't the second variable occupying any space at all (which seems like the case)?

It's a C99 flexible array member - that's the entire point of it. The idea is to allocate your structure something like:

struct smth *s = malloc(sizeof *s + 10 * sizeof s->b[0]);

And then you'd have a structure that operates as if b were a 10-element array.

like image 75
Carl Norum Avatar answered Nov 11 '22 07:11

Carl Norum


Because the size of the member b is zero, and the compiler adds padding between the a and b members so that b is on a "word" boundary.

However, if I remember correctly having a flexible array in a structure like that is only valid C, not C++ except as a compiler extension.

like image 45
Some programmer dude Avatar answered Nov 11 '22 09:11

Some programmer dude


Since OP comments that the question is C++:

struct smth
{
    char a;
    int b[];
};

An array like b[] is invalid in C++. The array must have fixed size. Variable length arrays are only valid in C99.

Assuming that your compiler supports it as extension, the array b[] has a size of zero, which makes the struct containing only a char member. The the rule of padding in struct works, padding the struct to a word, which is 4 bytes in your machine.

like image 2
Yu Hao Avatar answered Nov 11 '22 08:11

Yu Hao