CC
AdvancedLesson 17 of 18

Memory Layout, Padding & Qualifiers – C

Stack, heap and static memory; struct alignment; const, volatile and restrict.

A running program uses four regions: code (machine instructions, literals), data (global and static variables), stack (local variables and return addresses, grows with every function call) and heap (malloc, managed manually). The stack is small (often 8 MB) and fast, the heap large and flexible.

The compiler aligns fields to their natural alignment and inserts padding to do so. The order of the fields therefore affects the size of a struct:

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

struct A { char c; int i; char d; };   // c + 3 padding + i + d + 3 padding
struct B { int i; char c; char d; };   // i + c + d + 2 padding

int main(void) {
    // Typical 64-bit platform: int = 4 bytes, alignment 4
    printf("A: %zu  B: %zu\n", sizeof(struct A), sizeof(struct B));   // 12 8
    printf("offset i in A: %zu\n", offsetof(struct A, i));            // 4
    printf("offset d in A: %zu\n", offsetof(struct A, d));            // 8
    return 0;
}

Qualifiers give the compiler additional guarantees. const protects against accidental writes. With pointers, it matters where const is placed:

#include <stdio.h>

int main(void) {
    int x = 1, y = 2;
    const int *p1 = &x;         // value cannot be changed via p1, p1 itself can
    int *const p2 = &x;         // p2 cannot be redirected, value can be changed
    const int *const p3 = &x;   // both locked

    p1 = &y;                    // ok
    *p2 = 10;                   // ok
    // *p1 = 5;                 // error: read-only
    // p2 = &y;                 // error: p2 is constant
    printf("%d %d %d\n", *p1, *p2, *p3);   // 2 10 10
    return 0;
}

volatile says: "This value can change without the code doing it" (hardware registers, signal handlers). The compiler must then not optimize the accesses away. restrict promises that two pointers do not point to the same memory, which allows optimizations (e.g. in memcpy).

#include <stdio.h>
#include <signal.h>

volatile sig_atomic_t beenden = 0;

void handler(int sig) {
    (void)sig;
    beenden = 1;
}

int main(void) {
    signal(SIGINT, handler);
    raise(SIGINT);                       // triggers the handler immediately
    printf("beenden = %d\n", (int)beenden);   // 1
    return 0;
}
WarningNever return the address of a local variable: int *f(void) { int x = 5; return &x; } – after the return, x is gone and the pointer dangles. Equally dangerous are huge local arrays (char buf[10000000];) and unbounded recursion: they blow the stack.
Tipvolatile does not make code thread-safe. Since C11, there are <stdatomic.h> and <threads.h> for that.