Search code examples
cgcccompiler-optimizationmemory-alignment

No Memory Alignment with GCC


I am working with some packet data. I have created structs to hold the packet data. These structs have been generated by python for a specific networking protocol.

The issue is that due to the fact that the compiler aligns the structures, when I send the data via the networking protocol, the message ends up being longer than I would like. This causes the other device to not recognize the command.

Does anyone know possible a work around this so that my packers are exactly the size the struct should be or is there a way I can turn off memory alignment?


Solution

  • In GCC, you can use __attribute__((packed)). These days GCC supports #pragma pack, too.

    1. attribute documentation
    2. #pragma pack documentation

    Examples:

    1. attribute method:

      #include <stdio.h>
      
      struct packed
      {
          char a;
          int b;
      } __attribute__((packed));
      
      struct not_packed
      {
          char a;
          int b;
      };
      
      int main(void)
      {
          printf("Packed:     %zu\n", sizeof(struct packed));
          printf("Not Packed: %zu\n", sizeof(struct not_packed));
          return 0;
      }
      

      Output:

      $ make example && ./example
      cc     example.c   -o example
      Packed:     5
      Not Packed: 8
      
    2. pragma pack method:

      #include <stdio.h>
      
      #pragma pack(1)
      struct packed
      {
          char a;
          int b;
      };
      #pragma pack()
      
      struct not_packed
      {
          char a;
          int b;
      };
      
      int main(void)
      {
          printf("Packed:     %zu\n", sizeof(struct packed));
          printf("Not Packed: %zu\n", sizeof(struct not_packed));
          return 0;
      }
      

      Output:

      $ make example && ./example
      cc     example.c   -o example
      Packed:     5
      Not Packed: 8