Lack of memory alignment using GCC

I work with some batch data. I created structures for storing batch data. These structures were generated by python for a specific network protocol.

The problem is that due to the compiler aligning the structures, when I send data via the network protocol, the message ends longer than I would like. This causes the other device to not recognize the command.

Does anyone know if it is possible to do this so that my packers are exactly the size that the structure should be or is there a way to disable memory alignment?

+4
c compiler-optimization gcc compiler-construction memory-alignment
source share
1 answer

In GCC, you can use __attribute__((packed)) . Nowadays, GCC also supports the #pragma pack .

Examples:

  • 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 
  • 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 
+6
source share

All Articles