Part ofSystems Programming Companion, week 5
Defining Structs
C has no classes. What it does have is structs: custom types that bundle related fields under one roof.
Basic Struct Syntax
struct Point { int x; int y;};
struct Point p = {10, 20};printf("(%d, %d)\n", p.x, p.y);typedef for Convenience
Plain C makes you spell out struct Point everywhere. A typedef shortens it to plain Point:
typedef struct { int x; int y;} Point;
Point p = {10, 20};Structs and Memory Layout
Fields land in memory in declaration order, but the compiler is free to slip padding between them so each field sits on a CPU-friendly boundary:
struct Example { char a; // 1 byte // 3 bytes padding int b; // 4 bytes char c; // 1 byte // 3 bytes padding};// sizeof(struct Example) is typically 12, not 6Padding exists so misaligned loads don't force the CPU into slower fixup paths (or, on some architectures, outright traps). Result: sizeof(struct) is usually bigger than the bytes you can see. Order fields largest to smallest and you'll often shave the padding right back down.
Try it before you run any code. These are the four fields of struct Loose from the program below, laid out with x86-64 Linux sizes. Move them around and see how small you can get sizeof.
struct Loose
| Offset | Field | Size | Notes |
|---|---|---|---|
| 0x0 (0) | char a | 1 | |
| 0x1 (1) | padding | 7 | |
| 0x8 (8) | double d | 8 | |
| 0x10 (16) | char c | 1 | |
| 0x11 (17) | padding | 3 | |
| 0x14 (20) | int i | 4 |
sizeof = 24 bytes, 10 of them padding; alignment 8.
Reorder the fields and watch the padding change.
- char a
- double d
- char c
- int i
See it for yourself. offsetof from <stddef.h> reports where each field starts, so you can spot the holes:
On x86-64 the same four fields take 24 bytes in one order and 16 in the other. You could squash out every gap with #pragma pack(1), but then d sits at an odd address: each access gets slower, and on stricter CPUs a plain pointer to that field can trap.
Pointers to Structs
Once you're working through a struct pointer, swap the dot for the arrow:
Point *pp = &p;printf("(%d, %d)\n", pp->x, pp->y);// pp->x is shorthand for (*pp).xStructs on the Heap
Heap-allocate one with malloc:
Point *p = malloc(sizeof(Point));p->x = 10;p->y = 20;// ... use p ...free(p);That little pattern is the building block for nearly every data structure you'll write in C. Linked-list nodes, tree nodes, hash buckets — all of them are heap-allocated structs stitched together by pointers.
Padding Leaks Into Files
Sooner or later a struct needs to leave the process: written to disk, or sent over a socket. The tempting one-liner is fwrite(&rec, sizeof rec, 1, f). It copies the struct byte for byte, padding and all, in whatever byte order this CPU happens to use. A reader compiled for a different machine, or with different packing, gets garbage.
Suppose the format says a record is exactly 7 bytes: a 1-byte type, a 4-byte id and a 2-byte length, with multi-byte numbers big-endian (most significant byte first, the usual network order). The program below dumps what the struct really holds next to what serialise produces. Right now serialise takes the shortcut.
On x86-64 the struct is 12 bytes. The aa bytes are padding the format never asked for, and 78 56 34 12 is the id stored little-endian. Both would end up in the file.
Show one way to write serialise()
size_t serialise(const struct Record *r, uint8_t *out) { out[0] = r->type; out[1] = (uint8_t)(r->id >> 24); out[2] = (uint8_t)(r->id >> 16); out[3] = (uint8_t)(r->id >> 8); out[4] = (uint8_t)r->id; out[5] = (uint8_t)(r->len >> 8); out[6] = (uint8_t)r->len; return 7;}Shifts work on values, so this code produces the same bytes on any CPU, whatever its endianness or padding rules. The reading side does the reverse: id = (uint32_t)in[1] << 24 | (uint32_t)in[2] << 16 | (uint32_t)in[3] << 8 | in[4];. The cast before shifting matters, because in[1] << 24 on its own is done in int and can overflow. The file I/O lesson comes back to this when you write whole files of records.