CC

C: More snippets – code examples

Contents

Errors via return value and errno

Error handling#errno#error#fopen#strerrorCompare in all languages
Use case: Detect and report failed file accesses and system calls.
#include <stdio.h>
#include <errno.h>
#include <string.h>

int main(void) {
    FILE *f = fopen("does-not-exist.txt", "r");
    if (f == NULL) {
        printf("Error %d: %s\n", errno, strerror(errno));
        return 1;
    }
    fclose(f);
    return 0;
}

C has no exceptions. Functions report errors via return values (NULL, -1); the cause is in errno, and strerror turns it into text. The caller has to check every error itself.

Parsing a number from text (strtol)

Error handling#strtol#parsing#atoi
Use case: Convert user input or configuration values into numbers and detect errors.
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    const char *s = "42abc";
    char *rest;
    long zahl = strtol(s, &rest, 10);
    printf("Number: %ld, Rest: \"%s\"\n", zahl, rest);
    return 0;
}

Unlike atoi, strtol tells you via rest how far the conversion got (*rest == '\0' means: everything was used). For overflow, also check errno.

Swapping values via pointers

Pointers#pointer#swap#call by reference
Use case: Change values of a calling function (call by reference), e.g. in sorting algorithms.
#include <stdio.h>

void tausche(int *a, int *b) {
    int t = *a;
    *a = *b;
    *b = t;
}

int main(void) {
    int x = 1, y = 2;
    tausche(&x, &y);
    printf("%d %d\n", x, y);
    return 0;
}

&x passes the address, *a accesses it. Without pointers, tausche would only swap copies.

Command-line arguments

Tools#argc#argv#cli
Use case: Build your own CLI tools that accept file names or options.
#include <stdio.h>

int main(int argc, char *argv[]) {
    printf("Program: %s, Arguments: %d\n", argv[0], argc - 1);
    for (int i = 1; i < argc; i++) {
        printf("  argv[%d] = %s\n", i, argv[i]);
    }
    return 0;
}

argc counts the arguments (including the program name), argv is an array of strings. Call it e.g. as ./tool eins zwei. You convert numbers with strtol.

Dynamic array with calloc

Memory#calloc#malloc#free#heap
Use case: Store amounts of data whose size is only known at runtime (e.g. number of measurements).
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    size_t n = 5;
    double *w = calloc(n, sizeof *w);
    if (w == NULL) return 1;
    for (size_t i = 0; i < n; i++) w[i] = i * 1.5;
    double summe = 0;
    for (size_t i = 0; i < n; i++) summe += w[i];
    printf("Average: %.2f\n", summe / n);
    free(w);
    return 0;
}

calloc(n, size) returns zero-initialized memory and checks the multiplication for overflow. Always check for NULL and release with free.

Growing array (vector) with realloc

Memory#realloc#vector#dynamic#struct
Use case: A list that grows while reading input, without knowing the number of elements beforehand.
#include <stdio.h>
#include <stdlib.h>

typedef struct { int *daten; size_t len, cap; } Vec;

int vec_push(Vec *v, int x) {
    if (v->len == v->cap) {
        size_t neu = v->cap ? v->cap * 2 : 4;
        int *tmp = realloc(v->daten, neu * sizeof *tmp);
        if (tmp == NULL) return -1;
        v->daten = tmp;
        v->cap = neu;
    }
    v->daten[v->len++] = x;
    return 0;
}

int main(void) {
    Vec v = {NULL, 0, 0};
    for (int i = 1; i <= 10; i++) {
        if (vec_push(&v, i * i) != 0) { free(v.daten); return 1; }
    }
    printf("len=%zu cap=%zu last=%d\n", v.len, v.cap, v.daten[v.len - 1]);
    free(v.daten);
    return 0;
}

When the array is full, the capacity is doubled. realloc is first assigned to a helper variable so that the old block is not lost on failure.

Setting and testing bit flags

Bits#bits#flags#bitmask
Use case: Store options, permissions or states compactly in a single number (file permissions, hardware registers).
#include <stdio.h>
#include <stdint.h>

enum { LESEN = 1u << 0, SCHREIBEN = 1u << 1, AUSFUEHREN = 1u << 2 };

int main(void) {
    uint8_t rechte = LESEN | SCHREIBEN;   // 011
    rechte &= ~SCHREIBEN;                 // clear bit -> 001
    rechte ^= AUSFUEHREN;                 // toggle    -> 101
    printf("%d\n", rechte);               // 5
    printf("read=%d write=%d\n", (rechte & LESEN) != 0, (rechte & SCHREIBEN) != 0);
    return 0;
}

| sets, & ~ clears, ^ toggles, & tests. Unsigned types are the safe choice for bit operations.

Macros: parentheses are mandatory

Preprocessor#define#macro#preprocessor
Use case: Write small helper macros safely and avoid a typical trap.
#include <stdio.h>

#define QUAD_FALSCH(x) x * x
#define QUAD(x) ((x) * (x))

int main(void) {
    printf("%d\n", QUAD_FALSCH(2 + 1));   // 2 + 1 * 2 + 1 = 5
    printf("%d\n", QUAD(2 + 1));          // 9
    return 0;
}

Macros only replace text without respecting precedence. Put parentheses around parameters and the whole result. Better: static inline int quad(int x).

Header with include guard

Preprocessor#header#include#guard
Use case: Provide a library's declarations without multiple includes causing errors.
/* vektor.h */
#ifndef VEKTOR_H
#define VEKTOR_H

#include <stddef.h>

typedef struct { double x, y; } Vektor;

Vektor vektor_add(Vektor a, Vektor b);
double vektor_laenge(Vektor v);

#endif /* VEKTOR_H */

An include guard prevents duplicate definitions when a header is included multiple times. The implementation lives in vektor.c, which contains #include "vektor.h". Alternatively, not standardized: #pragma once.

Finding a buffer overflow with AddressSanitizer

Security#asan#sanitizer#buffer overflow#debugging
Use case: Automatically track down memory errors during development before they become security vulnerabilities in production.
#include <stdlib.h>

int main(void) {
    int *a = malloc(3 * sizeof *a);
    a[3] = 42;          /* ERROR: only indices 0..2 are valid */
    free(a);
    return 0;
}
/* Compile and run:
   gcc -g -fsanitize=address -o demo demo.c && ./demo
   -> "heap-buffer-overflow ... WRITE of size 4" with line number */

This program deliberately contains undefined behavior: the write access lies one element beyond the block. Without a sanitizer it often runs "normally" – with -fsanitize=address it aborts immediately with a precise diagnosis.