bhylu.com

Advertisements

C Structure Padding and Alignment

Inspect safe layout relationships without turning native structure bytes into a file format.

How it works

Compilers may insert padding between structure members and after the last member to satisfy alignment requirements. offsetof reports a member offset, sizeof reports complete object size and _Alignof reports an alignment requirement. These are useful for inspecting a local ABI, not a portable serialization specification. Padding bytes need not have a stable meaningful value. A binary comparison of two structures can therefore disagree even when all their meaningful member values are equal.

Run it locally

Use a hosted C17 compiler in a separate lab folder. The command assumes a driver named cc; substitute gcc, clang or zig cc as appropriate. C does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed for these C programs.

cc -std=c17 -Wall -Wextra -Wpedantic -Werror layout-padding.c -o lesson

On Windows, use -o lesson.exe and run .\lesson.exe in PowerShell. On Unix-like systems run ./lesson. Math-library linking differs by toolchain; GCC on many Unix systems needs -lm after the source.

Download the complete C source. File-writing labs must run in an empty private directory, away from existing reports.

Example

C17 · layout-padding.c

#include <stdio.h>
#include <stddef.h>

struct Record { char code; int depth; };

int main(void) {
    printf("First member starts at zero: %d\n", offsetof(struct Record, code) == 0);
    printf("Depth follows code: %d\n", offsetof(struct Record, depth) >= sizeof(char));
    printf("Object fits its members: %d\n", sizeof(struct Record) >= sizeof(char) + sizeof(int));
    printf("Alignment is positive: %d\n", _Alignof(struct Record) > 0);
    return 0;
}

Expected result

First member starts at zero: 1
Depth follows code: 1
Object fits its members: 1
Alignment is positive: 1

The output tests relationships rather than assuming one platform offset or size. Reordering fields can change layout, but performance should be measured before making readability or compatibility tradeoffs. For a portable file, encode each field deliberately with a defined byte order, width and version. Text records are often simpler for small teaching tools.

For language and library rules, consult the WG14 C working group and its public C11 committee draft, which describes the core facilities used here; C17 incorporates corrections. Check your compiler and runtime documentation for implementation details.

Advertisements