Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does sizeof calculate the size of structures

I know that a char and an int are calculated as being 8 bytes on 32 bit architectures due to alignment, but I recently came across a situation where a structure with 3 shorts was reported as being 6 bytes by the sizeof operator. Code is as follows:

#include <iostream>
using namespace std ;

struct IntAndChar
{
    int a ;
    unsigned char b ;
};


struct ThreeShorts
{
    unsigned short a ;
    unsigned short b ;
    unsigned short c ;
};


int main()
{
    cout<<sizeof(IntAndChar)<<endl; // outputs '8'
    cout<<sizeof(ThreeShorts)<<endl; // outputs '6', I expected this to be '8'
    return 0 ;
}

Compiler : g++ (Debian 4.3.2-1.1) 4.3.2. This really puzzles me, why isn't alignment enforced for the structure containing 3 shorts?

like image 467
Gearoid Murphy Avatar asked Apr 17 '10 19:04

Gearoid Murphy


People also ask

What do you mean by size of structure?

Size of the struct should be sum of all the data member, which is: Size of int n1+ size of int* n2 +size of char c1+ size of char* c2. Now considering the 64-bit system, Size of int is 4 Bytes. Size of character is 1 Byte. Size of any pointer type is 8 Bytes.

How the size of the structure defined in C programming?

The size of the entire structure is 8 bytes. On knowing the structured padding, it is easier to redesign or rewrite the structure.


1 Answers

That's because int is 4 bytes, and has to be aligned to a 4-bytes boundary. This means that ANY struct containing an int also has to be aligned to at least 4-bytes.

On the other hand, short is 2 bytes, and needs alignment only to a 2-bytes boundary. If a struct containing shorts does not contain anything that needs a larger alignment, the struct will also be aligned to 2-bytes.

like image 62
slacker Avatar answered Sep 24 '22 19:09

slacker