Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this struct definition add extra one byte of memory usage?

#include <stdio.h>
typedef struct {
    short x,y;
    char type;
} Tile;

int main(int argc, const char *argv[])
{
    printf("%d\n",sizeof(short));
    printf("%d\n",sizeof(char));
    printf("%d\n",sizeof(Tile));
    return 0;
}

The output is:

2
1
6

I expected sizeof(Tile) to be 5, instead of 6. Is this a well-defined behaviour that structs add one extra byte of memory usage, or is it implementation dependant?

like image 620
yasar Avatar asked Oct 28 '25 19:10

yasar


1 Answers

It's because of padding (kind of like rounding).

for example:

struct example1
{
    char a;
    int b;
    char c;
}

struct example2
{
    char a;
    char b;
    int c;
}

will likely differ in size, first will have size of 12B, second will likely only eat 8B (arch and compiler dependant).

Edit: gcc does padding by size of biggest memeber of struct.

Gcc can minimize this behavior by option -fpack-struct, however this may not be best idea ever, it could even backfire (network protocol implementantion is first thing that pops into my mind).

like image 100
Tomas Pruzina Avatar answered Oct 30 '25 12:10

Tomas Pruzina