Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does 'sizeof' give wrong measurement? [duplicate]

Tags:

c++

struct

sizeof

Possible Duplicate:
struct sizeof result not expected

I have this C++ struct:

struct bmp_header {

  //bitmap file header (14 bytes)
  char Sign1,Sign2; //2
  unsigned int File_Size; //4
  unsigned int Reserved_Dword; //4
  unsigned int Data_Offset; //4

  //bitmap info header (16 bytes)
  unsigned int Dib_Info_Size; //4
  unsigned int Image_Width; //4
  unsigned int Image_Height; //4

  unsigned short Planes; //2
  unsigned short Bits; //2  
};

It is supposed to be 30 bytes, but 'sizeof(bmp_header)' gives me value 32. What's wrong?

like image 725
jondinham Avatar asked Sep 08 '11 16:09

jondinham


3 Answers

It doesn't give a wrong measurement. You need to learn about alignment and padding.

The compiler can add padding in between structure members to respect alignment constraints. That said, it's possible to control padding with compiler specific directives (see GCC variable attributes or MSVC++ pragmas).

like image 135
Gregory Pakosz Avatar answered Nov 10 '22 15:11

Gregory Pakosz


The reason is because of padding. If you put the chars at the end of the struct, sizeof will probably give you 30 bytes. Integers are generally stored on memory addresses that are multiples of 4. Therefore, since the chars take up 2 bytes, there are two unused bytes between it and the first unsigned int. char, unlike int, is not usually padded.

In general, if space is a big concern, always order elements of structs from largest in size to smallest.

Note that padding is NOT always (or usually) the sizeof(element). It is a coincidence that int is aligned on 4 bytes and char is aligned on 1 byte.

like image 34
Daniel Avatar answered Nov 10 '22 15:11

Daniel


struct bmp_header {

  char Sign1,Sign2; //2
  // padding for 4 byte alignment of int: // 2
  unsigned int File_Size; //4
  unsigned int Reserved_Dword; //4
  unsigned int Data_Offset; //4

  unsigned int Dib_Info_Size; //4
  unsigned int Image_Width; //4
  unsigned int Image_Height; //4

  unsigned short Planes; //2
  unsigned short Bits; //2  
};

2+2+4+4+4+4+4+4+2+2 = 32. Looks correct to me. If you expect 30 it means you expect 1 byte padding, as in :

#pragma pack(push)
#pragma pack(1)

struct bmp_header {

  char Sign1,Sign2; //2
  unsigned int File_Size; //4
  unsigned int Reserved_Dword; //4
  unsigned int Data_Offset; //4

  unsigned int Dib_Info_Size; //4
  unsigned int Image_Width; //4
  unsigned int Image_Height; //4

  unsigned short Planes; //2
  unsigned short Bits; //2  
};

#pragma pack(pop)
like image 32
Remus Rusanu Avatar answered Nov 10 '22 17:11

Remus Rusanu