DM
Technical reference

C Cheatsheet

Systems programming fundamentals and memory safety

Must Know

bash

Compile and Run

Treat compiler warnings as problems to fix.

cc -std=c17 -Wall -Wextra -Wpedantic -O2 main.c -o app
./app
c

Pointers

& takes an address; * dereferences a pointer.

int value = 42;
int *pointer = &value;
printf("%d\n", *pointer);

Important Patterns

c

Allocate Safely

Every successful allocation needs a clear owner and cleanup.

size_t count = 10;
int *items = calloc(count, sizeof *items);
if (items == NULL) return EXIT_FAILURE;

free(items);
items = NULL;
c

Bounded Formatting

Prefer bounded APIs and check truncation.

char buffer[64];
int written = snprintf(buffer, sizeof buffer, "user-%d", id);
if (written < 0 || (size_t) written >= sizeof buffer) { /* truncated */ }

Useful Recipes

c

Dynamic Array Growth

Assign realloc to a temporary pointer.

if (length == capacity) {
    size_t next = capacity ? capacity * 2 : 8;
    void *temp = realloc(items, next * sizeof *items);
    if (!temp) goto cleanup;
    items = temp;
    capacity = next;
}
c

Read Lines

char *line = NULL;
size_t size = 0;
while (getline(&line, &size, stdin) != -1) { /* use line */ }
free(line);

Pitfalls & Production

Undefined Behavior

Undefined behavior can appear to work until optimization or input changes.

out-of-bounds access
use after free
signed overflow
invalid shifts
uninitialized reads
bash

Sanitizers

Use sanitizers in development and CI.

cc -g -fsanitize=address,undefined main.c -o app
./app
valgrind --leak-check=full ./app