kesari
kesari

Reputation: 576

sizeof(struct) not following padding

Consider,

#include<stdio.h>

struct outside1
{
    int a;
    char b;
    char c;
    char d[3];
};

struct outside2
{
    char a,b,A[2];
    char B[2];
};

int main()
{
    printf("%zu %zu\n",sizeof(struct outside1),sizeof(struct outside2));
    return 0;
}

By predicting the output using the padding concepts, it would be "12 8". But the actual output is "12 6".

Using gcc 4.7.2 Debian

Can anyone explain this ?

-Newbie

Upvotes: 1

Views: 165

Answers (2)

Keith Thompson
Keith Thompson

Reputation: 263237

struct outside2
{
    char a,b,A[2];
    char B[2];
};

You expect this structure to have a size of 8 bytes; in fact, its size is 6 bytes (on your implementation).

There's no need for any additional padding. An array of any type has the same alignment requirement as the element type, which means that A and B only require byte alignment.

There are a total of 6 char members or submembers in the structure. Since no padding is required, the total size is 6 bytes.

A compiler could add, say, another 2 bytes of padding at the end. It might do so if, for example, it requires all structures, or all structures above some size, to have at least 4-byte alignment. But the compiler you're using doesn't happen to do so.

The specific alignment and padding requirements can of course vary from one system to another; they're enforced by each compiler, and probably defined by the ABI for the platform.

Upvotes: 1

Deduplicator
Deduplicator

Reputation: 45654

char and int have an alignment requirement of their own size on virtually any implementation.

sizeof(char) is 1 per standard, common sizes for int are 1, 2 and 4.

That leads to common sizes for outside1 of 6, 8, 12.
And for outside2of 6.

BTW: The compiler is allowed to insert any amount of padding after every structure member, though it normally uses the minimum neccessary to account for alignment restriction, in order to easily follow the "common initial subsequence"-rule.

Also, since C99 or thereabouts alignments are restricted to powers of 2, and the object size must be evenly divisable by it.

Upvotes: 3

Related Questions