Skip to content
systemcoding.dev
Systems Programming

Use malloc, calloc, realloc and free Correctly

Build a program that reads any number of integers from input, using malloc, calloc, realloc and free the right way, with the checks that prevent crashes.

7 min read
Summarize in AI
Flat illustration of heap memory as allocated and free blocks, with the C, Rust and C++ logos.

Reading a list of numbers when you do not know how many are coming is the task that forces every C programmer to learn dynamic allocation. A fixed array of 100 either wastes space or overflows on the 101st value, and the standard answer is memory that grows as input arrives. This post builds that program step by step, using each of the four functions where it fits, and for each step shows the mistake that the beginner version makes and the check that prevents it. By the end you will have a complete program that reads integers from standard input until it runs out, stores them, and prints their sum and the largest.

The code is C17, compiled with GCC 14 on glibc 2.40 under Linux 6.12. It follows ISO C and POSIX.1-2024, so it behaves the same on macOS and the BSDs, except where the text says otherwise. For the wider picture, see the guide to dynamic memory allocation in C, which this post applies to one task.

The four functions in one table

FunctionWhat it doesMemory contentsOn failure
malloc(n)Allocates n bytesIndeterminateReturns NULL
calloc(count, size)Allocates count * size bytes, checking the multiplicationAll zero bytesReturns NULL
realloc(p, n)Resizes the block at p to n bytes, possibly moving itOld contents kept, new part indeterminateReturns NULL, old block untouched
free(p)Releases the block at pGone, do not touchNothing, free(NULL) is safe

Every allocation function takes a size in bytes. That makes sizeof the most useful tool you have: write sizeof *items, the size of whatever the pointer points to, and never type a number of bytes by hand.

Step 1: start with a small block

The program starts with room for four integers and remembers two numbers, how many it holds (count) and how many it has room for (capacity). Keeping both is the heart of every growing buffer.

numbers_step1.cc
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    size_t capacity = 4;
    size_t count = 0;
    int *items = malloc(capacity * sizeof *items);

    if (items == NULL) {
        fprintf(stderr, "cannot allocate the initial buffer\n");
        return EXIT_FAILURE;
    }
    printf("room for %zu integers, holding %zu\n", capacity, count);
    free(items);
    return EXIT_SUCCESS;
}
Text
room for 4 integers, holding 0

Two habits are already in place. The result of malloc() is checked against NULL before use, and the size is capacity * sizeof *items, so changing int to long later changes the allocation with it. The block is freed before the program ends. Freeing at exit is not strictly needed, since the operating system reclaims everything, but it keeps leak checkers quiet and makes the code reusable as a function.

Step 2: read input and grow when full

Now read integers with scanf() and store each one. When count reaches capacity, double the capacity with realloc(). The temporary pointer matters here: if realloc() fails it returns NULL and leaves the old block alone, so assigning the result straight to items would lose the only pointer to a block that is still allocated.

numbers_step2.cc
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    size_t capacity = 4;
    size_t count = 0;
    int *items = malloc(capacity * sizeof *items);
    int value;

    if (items == NULL) {
        return EXIT_FAILURE;
    }

    while (scanf("%d", &value) == 1) {
        if (count == capacity) {
            size_t bigger = capacity * 2;
            int *tmp = realloc(items, bigger * sizeof *items);

            if (tmp == NULL) {
                free(items);                 /* the old block is still ours */
                fprintf(stderr, "out of memory after %zu values\n", count);
                return EXIT_FAILURE;
            }
            items = tmp;
            capacity = bigger;
        }
        items[count++] = value;
    }

    printf("read %zu values, capacity %zu\n", count, capacity);
    free(items);
    return EXIT_SUCCESS;
}

Feed it ten numbers, such as printf '3 9 4 1 7 2 8 6 5 10' | ./numbers_step2:

Text
read 10 values, capacity 16

The capacity went 4, 8, 16, so the buffer was reallocated twice for ten values. Doubling is the choice that matters. Growing by a fixed amount such as 4 each time would reallocate and possibly copy the whole array every four values, which turns reading n numbers into quadratic work. Doubling keeps the total copying proportional to n.

Notice what the loop does not do. It never keeps a pointer to an individual element across a realloc(). After a block moves, any such pointer is dangling, and the safe habit is to keep indexes, not pointers, into a growing array.

Step 3: use the data, then release it

Computing the sum and maximum is ordinary code. The part to add is a guard for empty input, since reading the maximum of zero values would read items[0], memory the program never wrote.

numbers_final.cc
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    size_t capacity = 4;
    size_t count = 0;
    int *items = malloc(capacity * sizeof *items);
    long long sum = 0;
    int largest = INT_MIN;
    int value;

    if (items == NULL) {
        return EXIT_FAILURE;
    }
    while (scanf("%d", &value) == 1) {
        if (count == capacity) {
            int *tmp = realloc(items, capacity * 2 * sizeof *items);

            if (tmp == NULL) {
                free(items);
                return EXIT_FAILURE;
            }
            items = tmp;
            capacity *= 2;
        }
        items[count++] = value;
    }

    if (count == 0) {
        puts("no input");
        free(items);
        return EXIT_SUCCESS;
    }
    for (size_t i = 0; i < count; i++) {
        sum += items[i];
        if (items[i] > largest) {
            largest = items[i];
        }
    }
    printf("count=%zu sum=%lld largest=%d\n", count, sum, largest);

    free(items);
    items = NULL;
    return EXIT_SUCCESS;
}

With the same ten numbers as input (3, 9, 4, 1, 7, 2, 8, 6, 5, 10, which sum to 55):

Text
count=10 sum=55 largest=10

With empty input, the program prints no input. The sum uses long long so a large list of large integers does not overflow an int accumulator, a separate bug that has nothing to do with allocation and is easy to miss.

Where calloc fits

calloc() earns its place when you want zeroed memory or an array whose size comes from outside. In the program above it would replace the initial malloc(), but there the zeroing is wasted, because every slot is written before it is read. A better use is a histogram, where zero is the correct starting value:

histogram.cc
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    const char *text = "systems programming";
    size_t *freq = calloc(256, sizeof *freq);

    if (freq == NULL) {
        return EXIT_FAILURE;
    }
    for (const char *p = text; *p != '\0'; p++) {
        freq[(unsigned char)*p]++;
    }
    for (int c = 'a'; c <= 'z'; c++) {
        if (freq[c] > 1) {
            printf("%c appears %zu times\n", c, freq[c]);
        }
    }
    free(freq);
    return EXIT_SUCCESS;
}
Text
g appears 2 times
m appears 3 times
r appears 2 times
s appears 3 times

Count them against the input to see the loop is right: systems has three s and one m, and programming has two each of r, g and m, so m totals three. Letters that appear once are skipped by the freq[c] > 1 test. Every counter started at zero without a single line of initialization code, and that is the whole point of choosing calloc() here.

What the library says when you get it wrong

The glibc allocator checks for some misuse when you call free() and aborts with a message. Knowing the messages saves time:

MessageMeaning
free(): double free detected in tcache 2The same block was freed twice
free(): invalid pointerThe pointer was not returned by an allocation function
free(): invalid sizeThe block's header was overwritten, often by an overflow before it
malloc(): corrupted top sizeSomething wrote past the end of the last block in the heap
realloc(): invalid pointerrealloc() got a pointer that was not an allocation

Each is followed by Aborted (core dumped). These checks are best-effort. A bug that glibc does not notice just corrupts data, which is why tests should also run under AddressSanitizer.

A short checklist for each call

  • After malloc() or calloc(): compare with NULL, then use.

  • Before realloc(): assign the result to a temporary, check it, then update the real pointer and the capacity together.

  • After free(): do not touch the pointer again; set it to NULL if the variable lives on.

  • Always: size with sizeof *pointer, and free each block exactly once.

Testing the program with awkward input

A growing buffer is correct only if it survives the inputs that stress it. Feed the program three cases and check each result against your own arithmetic. First, an empty input, which must print no input and not read the first slot. Second, exactly four numbers, which fill the initial capacity without a reallocation, and exactly five, which trigger the first one: a bug in the growth condition usually shows at that boundary, as an off-by-one that writes slot four before the block has room. Third, a long run, such as a hundred thousand numbers generated with seq 1 100000 | ./numbers_final, where the sum is 5,000,050,000 and the largest is 100,000. The sum exceeds what a 32-bit int can hold, which is why the accumulator is a long long, and the long run is what reveals an accumulator that was left too small.

Text
count=100000 sum=5000050000 largest=100000

Then run the same cases under AddressSanitizer by compiling with -fsanitize=address. A program that passes the arithmetic and still reports a heap overflow at count 5 has a growth check that fires one element too late.

Taggedcbeginner
Share

Keep reading

Flat illustration of two options weighed side by side, with the macOS, Linux and Apple logos.
Kernels

Mach Traps vs BSD System Calls on macOS

Learn how macOS routes one trap instruction to either a Mach trap or a BSD system call, how the number sign and class decide, and why you should call libSystem.

8 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.