Why is the size of a struct not the sum of the sizes of its variables?

Asked

Viewed 1,023 times

4

For example, the following code:

#include <stdio.h>

struct exemplo{
    char letra;
    int numero;
    float flutuante;
};

int main()
{
    printf("Tamanho do char: %u\n", sizeof(char));
    printf("Tamanho do int: %u\n", sizeof(int));
    printf("Tamanho do float: %u\n", sizeof(float));
    printf("Tamanho da struct: %u\n", sizeof(struct exemplo));
}

Show on console:

Tamanho do char: 1
Tamanho do int: 4
Tamanho do float: 4
Tamanho da struct: 12

That is, the struct size is 12 and not 9 (1+4+4) as expected. Why does this happen?

1 answer

7


In fact the structure may be the same size as the sum of its members. It depends on the alignment. If the members allow to assemble the structure in an aligned way will have the same size.

The case presented really requires aligning the type char for a word, then there is a waste of space. This is called padding. The bytes used for the padding are not used, indicate nothing. And there is no problem in that, it is the normal one. It is done assom for performance issues. In most cases the compiler knows how to do better than the programmer.

If you need something different can be solved with #pragma pack(1) or __attribute__((packed)). More information can be obtained in the answer linked above. Rarely is this really necessary and it is better not to touch it if you do not understand all the implications it will have.

  • I would not say that it is rarely used,if you are going to transmit data over a network, for example, it will be of paramount importance to know how the data is arranged in memory.

  • Yes, this is a case, but consider all operations that are done in memory in a trivial way and this use. The disproportion is brutal, which makes it rare. Of course the rare is not in the sense of not doing, never need, only that there are few situations where it really is necessary, considering everything where structures are used.

  • if "you will transfer data over a network" - you have to adopt a well-defined serialization protocol. You can select one out of dozens of existing protocols, or create your ad-hoc. If you choose to create your own, you have to know things like padding, and other things that change the arrangement of data in memory - and that’s why it’s best to use an existing set of tools, usually with a few months or years of work to know all the corner cases, than go out doing your na crazy.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.