Computer Scientist, Graduate Student, and Geek

Tag: c

Preventing Auto-Padding in C Structures

January 05, 2010

Most networking applications written in C use structures to easily access the data in a packet header. If all the pieces are appropriately word aligned (i.e. one or more sequential parts of the header total 4-bytes in length), then a regular C structure works just fine. The standard IP, TCP, and UDP headers are all word aligned.

However, the custom packet header I was using for a project was not word aligned. Using a regular structure without any special notation, caused the GNU C compiler (gcc) to automatically add padding to the structure to force one or more sequential variables to be 4-byte aligned. But, the packet should not contain this extra padding. The parts of the header need to be "packed."

To force an entire structure to be packed, add

__attribute__((packed))
at the end of the structure definition. For example:
struct mine { 
short a;
int b;
}__attribute__((packed));

It is important to note that not all architectures will allow "packed" structures. Most RISC architectures require that variables be word-aligned, and generate a fault when memory is read across two words. The x86 and x86_64 architectures allow non-word-aligned variables for backwards compatibility to earlier processor versions. Wikipedia has more details on data structure alignment.

(The original source of this solution is: http://tuxsudh.blogspot.com/2005/05/structure-packing-in-gcc.html)

Categories: Development, Networking

Tags: c