Dynamic memory

Allocate with malloc / calloc, grow with realloc, and release with free.

Runs in Zerethon IDE · C (GCC 14) Official C documentation ↗
main.c
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    size_t capacity = 2, size = 0;
    int *items = malloc(capacity * sizeof *items);
    if (!items) return 1;

    for (int v = 1; v <= 5; v++) {
        if (size == capacity) {
            capacity *= 2;
            int *bigger = realloc(items, capacity * sizeof *items);
            if (!bigger) {
                free(items);
                return 1;
            }
            items = bigger;
        }
        items[size++] = v * v;
    }
    for (size_t i = 0; i < size; i++) printf("%d ", items[i]);
    printf("(capacity %zu)\n", capacity);
    free(items);
    return 0;
}

Output

1 4 9 16 25 (capacity 8)
  • Check the result of malloc / realloc for NULL.
  • Every malloc needs one free; using memory after free (or freeing twice) is undefined behaviour.
  • Memory per run is limited, so a runaway allocation ends the program.