George
George

Reputation: 1273

sizeof(struct) returns unexpected value

This should be simple but I have no clue where to look for the issue:

I have a struct:

struct region
{
public:
    long long int x;
    long long int y;
    long long int width;
    long long int height;
    unsigned char scale;
};

When I do sizeof(region) it gives me 40 when I am expecting 33.

Any ideas?

(mingw gcc, win x64 os)

Upvotes: 12

Views: 3406

Answers (3)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361412

As others said, structs are padded for alignments, and such padding not only depends on the type of the members, but also on the order of the members in which they're defined.

For example, consider these two structs A and B as defined below. Both structs are identical in terms of members and types; the only difference is that the order in which members are defined isn't same:

struct A
{
    int i;
    int j;
    char c;
    char d;
};

struct B
{
    int i;
    char c;
    int j;
    char d;
};

Would the sizeof(A) be equal to sizeof(B) just because they've same number of members of same type? No. Try printing the size of each:

cout << "sizeof(A) = "<< sizeof(A) << endl;
cout << "sizeof(B) = "<< sizeof(B) << endl;

Output:

sizeof(A) = 12
sizeof(B) = 16

Surprised? See the output yourself : http://ideone.com/yCX4S

Upvotes: 5

Andr&#233; Caron
Andr&#233; Caron

Reputation: 45224

long long int values are 8 bytes each. scale is only 1 byte but is padded for alignments, so it effectively takes up 8 bytes too. 5*8 = 40.

Upvotes: 6

Claudiu
Claudiu

Reputation: 229361

It's padding the struct to fit an 8-byte boundary. So it actually is taking 40 bytes in memory - sizeof is returning the correct value.

If you want it to only take 33 bytes then specify the packed attribute:

struct region
{
public:
    long long int x;
    long long int y;
    long long int width;
    long long int height;
    unsigned char scale;
} __attribute__ ((packed));

Upvotes: 13

Related Questions