TExcelTAD
Home › Memory Safety & Binary Exploitation Concepts › How C Objects Map to Bytes

How C Objects Map to Bytes

A sanitizer report speaks in bytes: "WRITE of size 8 at offset 20 of a 24-byte region". To turn that back into "the code overwrote the flags field", you need to know how the compiler lays out C objects: how big each type is, where padding goes, in which order the bytes of a number are stored, and what an array or a pointer really is. This lesson builds that translation table on x86-64 Linux (the System V ABI), the platform of every session in this course. The C language side (types, struct, union) is in C Structures and C Unions.

Definitions

  • Size and alignment: every type has a size (sizeof) and an alignment (_Alignof); an object of alignment a starts at an address divisible by a. On x86-64: char 1/1, short 2/2, int 4/4, long, pointers and double 8/8.
  • Padding: unused bytes the compiler inserts between struct members so each member is aligned, and at the end so arrays of the struct stay aligned. Padding has no defined value.
  • offsetof(T, m): the byte offset of member m inside T, from <stddef.h>.
  • Little-endian: x86-64 and (normally) Arm store the least significant byte of a number first. 0x11223344 is the bytes 44 33 22 11.
  • Array: elements back to back, no header and no stored length. a[i] is defined as *(a + i): the address of a plus i * sizeof *a.
  • Pointer: an 8-byte address. It carries no size, no type check and no lifetime at run time.

A struct, byte by byte

The program prints the layout of a small record type such as a parser might use, then dumps the bytes of one record. It runs on Compiler Explorer:

c · try it yourself
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>

struct record {
    uint8_t  kind;        /* 1 byte */
    uint32_t length;      /* 4 bytes, needs 4-byte alignment */
    char     name[6];     /* 6 bytes */
    uint64_t id;          /* 8 bytes, needs 8-byte alignment */
};

int main(void) {
    printf("sizeof(struct record) = %zu, alignment %zu\n", sizeof(struct record), _Alignof(struct record));
    printf("kind @%zu  length @%zu  name @%zu  id @%zu\n",
           offsetof(struct record, kind), offsetof(struct record, length),
           offsetof(struct record, name), offsetof(struct record, id));

    struct record r;
    memset(&r, 0xEE, sizeof r);          /* mark padding so we can see it */
    r.kind = 7;
    r.length = 0x11223344;
    memcpy(r.name, "lab01", 6);
    r.id = 0x0102030405060708;
    const unsigned char *b = (const unsigned char *)&r;
    for (size_t i = 0; i < sizeof r; i++)
        printf("%02x%s", b[i], (i % 8 == 7) ? "\n" : " ");
    return 0;
}
sizeof(struct record) = 24, alignment 8
kind @0  length @4  name @8  id @16
07 ee ee ee 44 33 22 11
6c 61 62 30 31 00 ee ee
08 07 06 05 04 03 02 01

The struct holds 19 bytes of data in 24 bytes. kind is followed by 3 padding bytes (ee ee ee) because length must start at a multiple of 4; name ends at offset 14, so 2 more padding bytes come before id at 16. The numbers are stored little-endian: length = 44 33 22 11, id = 08 07 … 01. Now a report such as "WRITE of size 2 at offset 14" reads as "two bytes past name, into the padding before id", and one byte more would reach id.

The same layout in Python

Network code and file parsers are often prototyped in Python with struct, and a mismatch between the Python model and the C layout is a classic source of bugs. struct's @ prefix uses the native C alignment, < packs without padding:

python · try it yourself
import struct

native = struct.Struct("@B I 6s Q")     # same members as struct record, native alignment
packed = struct.Struct("<B I 6s Q")     # little-endian, no padding: a wire format

rec = (7, 0x11223344, b"lab01\0", 0x0102030405060708)
print("native size:", native.size, " packed size:", packed.size)
print("packed bytes:", packed.pack(*rec).hex(" "))

# A C program that memcpy's 19 wire bytes into the 24-byte struct misreads every field after kind:
wire = packed.pack(*rec) + bytes(native.size - packed.size)
kind, length, name, ident = native.unpack(wire)
print(f"read as native: kind={kind} length=0x{length:08x} name={name!r} id=0x{ident:016x}")
native size: 24  packed size: 19
packed bytes: 07 44 33 22 11 6c 61 62 30 31 00 08 07 06 05 04 03 02 01
read as native: kind=7 length=0x62616c11 name=b'01\x00\x08\x07\x06' id=0x0000000000010203

The wire format has no padding, so a C parser that copies 19 wire bytes over the 24-byte struct reads length as 0x62616c11 (bytes of length and name mixed), a value of 1.6 billion that will then be used as a size. Parsers must read fields one at a time at explicit offsets, not cast a byte buffer to a struct.

Why layout matters for security

  • Padding leaks. Padding isn't initialised by member assignments. Copying a whole struct to a user (a write(), a copy_to_user in a kernel, a network packet) sends the padding too, and with it old stack or heap bytes: an information leak (CWE-200, and uninitialised memory). Fix: memset the struct first, or initialise with = {0} and copy field by field.
  • Overflow targets. An overflow of name runs into id, inside the same object. ASan can't see it: the whole struct is one valid region (an intra-object overflow).
  • sizeof of a pointer. In a function that received char *buf, sizeof buf is 8, whatever the buffer's real size. Pass sizes explicitly.
  • Endianness and casts. Reading a uint32_t length from a network packet without ntohl reverses its bytes; casting an unaligned char * to uint32_t * is undefined behaviour (UBSan: misaligned address).

How layout bugs are detected

UBSan flags misaligned loads and out-of-bounds indexes of known arrays; ASan flags accesses past the whole object; MSan and Valgrind flag padding bytes read before being written. Static checks: _Static_assert(sizeof(struct record) == 24, "layout changed") and _Static_assert(offsetof(struct record, id) == 16, …) break the build when someone reorders fields of an on-disk or on-wire structure. pahole (from the dwarves package) prints every struct's holes from the debug information.

How they are fixed

Order members from largest to smallest alignment to remove holes, serialise field by field instead of memcpying structs to the outside world, zero-initialise everything that leaves the process, and keep the size of every buffer next to its pointer (Safe C Patterns).

Pitfalls

  • __attribute__((packed)) removes padding but makes members misaligned; taking a pointer to such a member and dereferencing it is undefined and crashes on some architectures.
  • Flexible array members (char data[]; at the end) have size 0 in sizeof; allocate sizeof(struct) + n.
  • Bit-fields have implementation-defined layout; never use them for wire formats.

Practice

1. Reorder struct record to remove all internal padding. What is its new size?

uint64_t id; uint32_t length; char name[6]; uint8_t kind; = 8 + 4 + 6 + 1 = 19 bytes of data, rounded up to the alignment of 8: 24 bytes. The padding moves to the end (5 bytes), which is still copied with the struct, so still zero it.

2. A report says "WRITE of size 4 at offset 20 of 24-byte region" in a struct record. Which field was written?

Bytes 20–23 are the upper half of id (16–23). A 4-byte write at offset 20 is inside the object, so ASan wouldn't report it at all; a write at offset 24 would be past the end.

3. What bytes does uint16_t port = 8080; occupy in memory on x86-64?

8080 = 0x1F90, stored little-endian as 90 1f. On the network (big-endian, htons) it is 1f 90.

Test yourself

How many padding bytes follow kind in struct record?

  1. 0
  2. 1
  3. 3
  4. 7

How is 0x11223344 stored in memory on x86-64?

  1. 11 22 33 44
  2. 44 33 22 11
  3. 33 44 11 22
  4. It depends on the compiler

Why can copying a whole struct to the network leak secrets?

  1. Structs are encrypted
  2. Padding bytes are never initialised by field assignments and carry old memory contents
  3. sizeof is wrong
  4. Endianness

Why didn't the Python model's misread of 19 wire bytes as a native struct produce an error?

  1. Python checks types
  2. Nothing in C or struct checks layout: the bytes are reinterpreted silently, giving a huge 'length'
  3. The struct sizes matched
  4. Little-endian prevents it