Search code examples
coptimizationstructure

Structure padding in C


I've read this about structure padding in C: http://bytes.com/topic/c/answers/543879-what-structure-padding and wrote this code after the article, what should print out size of 'struct pad' like 16 byte and the size of 'struct pad2' should be 12. -as I think. I compiled this code with gcc, with different levels of optimization, even the sizeof() operator gives me both of them 16 byte. Why is it?

This information is necessary for me because of PS3 machines, where the byte boundaries and exploitation of the full dma transfer is important:

#include <stdio.h>
#include <stdlib.h>

struct pad
{
    char  c1;  // 1 byte
    short s1;  // 2 byte
    short s2;  // 2 byte
    char  c2;  // 1 byte
    long  l1;  // 4 byte
    char  c3;  // 1 byte
};

struct pad2
{
    long  l1;
    short s1;
    short s2;
    char  c1;
    char  c2;
    char  c3;
};

int main(void)
{
    struct pad P1;
    printf("%d\n", sizeof(P1));

    struct pad P2;
    printf("%d\n", sizeof(P2));

    return EXIT_SUCCESS;
}

Solution

  • There are two tricks that can be used to owercome this problem

    1. Using directive #pragma pack(push, 1) and then #pragma pack(pop).

      Example:

      #pragma pack(push, 1)
      
      struct tight{
         short element_1;
         int *element_2;
      };
      #pragma pack(pop)
      
      struct not_tight{
         short element_1;
         int *element_2;
      };
      
    2. To check if the sizes of two structs are same during compilation use this trick

       char voidstr[(sizeof(struct1)==sizeof(struct2)) - 1]; //it will return error at compile time if this fail