Coding

Dynamic Memory Allocation in C: malloc, calloc, realloc, free

Dynamic memory allocation in C means asking for a block of memory while the program is running, using malloc, calloc or realloc, and giving it back with free. You use it when the size of your data is unknown until run time, or when the data must outlive the function that created it.

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

int main(void)
{
    size_t count = 4;
    int *scores = calloc(count, sizeof *scores);
    if (scores == NULL) {
        fprintf(stderr, "out of memory\n");
        return 1;
    }

    scores[0] = 90;
    scores[3] = 75;
    printf("%d %d %d\n", scores[0], scores[1], scores[3]);

    free(scores);
    return 0;
}

Example output:

90 0 75

What dynamic memory allocation means in C

The C language gives every object a storage duration. cppreference lists four: automatic, static, thread and allocated. A normal local variable has automatic duration: its storage is created when the enclosing block is entered and released when the block is left by any route, including return. Static objects last for the whole run of the program. Allocated storage is the one you control by hand: it begins when you call an allocation function and ends when you call free.

That is the whole idea. The C standard does not use the words "stack" and "heap". Most implementations keep automatic objects on a call stack and allocated blocks in a separate pool managed by the allocator, so the terms are common shorthand, but the guarantees you rely on are the storage durations.

When to use dynamic allocation instead of a normal array

A fixed array such as int scores[100]; has its size written into the source code. Reach for dynamic allocation in these cases:

  • The size is known only at run time. The number of lines in a file, or a count typed by the user.
  • The size changes. A list that grows as items are added.
  • The data must outlive the function. A function that builds a structure and returns it to its caller cannot return a pointer to its own local array, because that array is gone when the function returns.
  • The object is large or its number is unbounded. Nodes in a linked list or tree are created one at a time, as many as the data requires.

If none of these applies, a plain local array is simpler and cannot leak. Do not allocate dynamically out of habit.

The four functions

FunctionWhat it doesMemory contents
malloc(size)Allocates size bytes and returns a pointerUninitialized
calloc(n, size)Allocates an array of n elements of size bytes eachSet to zero
realloc(p, size)Changes the size of the block p points toOld data kept; new bytes uninitialized
free(p)Releases the block p points toNot applicable

All four are declared in <stdlib.h>. The Linux man page describes malloc as allocating "size bytes" and returning a pointer to the allocated memory, and says free releases the block. For calloc, it says that if the multiplication of the element count and size would overflow, calloc returns an error. That built-in check is a good reason to prefer calloc(n, size) over a hand-written malloc(n * size) when the count comes from outside your program.

The detailed rules for each call, with leak-hunting tools, are in the malloc in C article. This page covers how the pieces fit together.

Always check for NULL

The man page says that on error these functions "return NULL and set errno", and lists ENOMEM, out of memory, as the error. Test the result before you use it:

char *line = malloc(length + 1);
if (line == NULL) {
    return -1;   /* let the caller decide what to do */
}

Writing through a NULL pointer is undefined behavior. Allocation failures are rare on a desktop and common in constrained places, such as a container with a memory limit, so code that never checks may pass every test and still fail in production.

How to grow an array with realloc

A frequent real-world task is reading values until the input ends, when you cannot know how many there will be. Start small, and double the capacity whenever the array is full:

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

int main(void)
{
    size_t capacity = 2;
    size_t length = 0;
    int *values = malloc(capacity * sizeof *values);
    if (values == NULL)
        return 1;

    int input;
    while (scanf("%d", &input) == 1) {
        if (length == capacity) {
            size_t new_capacity = capacity * 2;
            int *grown = realloc(values, new_capacity * sizeof *grown);
            if (grown == NULL) {
                free(values);
                return 1;
            }
            values = grown;
            capacity = new_capacity;
        }
        values[length++] = input;
    }

    printf("read %zu values\n", length);
    free(values);
    return 0;
}

Piping in the text 5 8 13 21 34 gives this example output:

read 5 values

Two details matter. First, the result of realloc goes into a temporary variable, grown. If you wrote values = realloc(values, ...) and the call failed, you would overwrite your only pointer with NULL and lose the original block. Second, the block may move, so after a successful realloc the old pointer must not be used again. Doubling keeps the number of reallocations small compared with growing by one element each time. The same pattern, wrapped in a struct, is what a dynamic array in C does.

The man page also documents reallocarray, which resizes like realloc but takes an element count and size. As with calloc, it reports an error instead of silently wrapping when that multiplication overflows. It is documented in the Linux man page rather than in the core C standard library list, so check that your platform provides it.

Who owns the memory

C will not tell you which part of the program is responsible for freeing a block. You have to decide, and write it down. A workable rule: whoever allocates a block, or receives it with a documented transfer of ownership, frees it. For example, a function named make_name that returns a heap string should say in its comment that the caller must call free.

When a struct holds pointers to blocks it owns, give it a matching destroy function that frees the inner blocks first and then the struct itself. Linked structures are the usual case, as in a linked list in C, where every node comes from its own allocation and has to be freed one by one while you still hold the pointer to the next node.

struct node {
    int value;
    struct node *next;
};

void list_free(struct node *head)
{
    while (head != NULL) {
        struct node *next = head->next;  /* save before freeing */
        free(head);
        head = next;
    }
}

The mistakes that dynamic allocation introduces

  • Memory leak. A block is allocated and never freed, and no pointer to it remains. Typical cause: an early return on an error path.
  • Use after free. Reading or writing through a pointer after free. Setting the pointer to NULL right after freeing it makes the bug fail immediately instead of corrupting data quietly.
  • Double free. Calling free twice on the same pointer is undefined behavior. The man page says free(NULL) does nothing, so a pointer set to NULL is safe to free again.
  • Freeing something that was not allocated. A local variable's address, a string literal, or a pointer into the middle of a block cannot be passed to free.
  • Wrong size. Use sizeof *pointer instead of a type name, and remember that a copy of a C string needs strlen(text) + 1 bytes for the terminating '\0'. See strings in C for why.
  • Using sizeof on a pointer parameter. It gives the size of the pointer, not of the block it points to. Pass the length separately.

Dynamic allocation compared with local variables

QuestionLocal (automatic)Dynamic (allocated)
When is it released?When the block is leftWhen you call free
Can the size be chosen at run time?Only with variable-length arrays, which are an exception to the usual ruleYes
Can it outlive the function?NoYes
Can the allocation fail?Not reported with a return valueYes, you get NULL
Who cleans up?The languageYou

The cppreference page notes that for variable-length arrays, storage is allocated when the declaration executes and deallocated when the declaration goes out of scope. That is still automatic duration, so such an array cannot be returned from the function either.

How to keep allocation under control

  • Allocate and free in the same function whenever you can. The matching free is then visible on the same screen.
  • Use one cleanup section for functions with several allocations: each failure jumps to a label that frees everything obtained so far, in reverse order.
  • Check each call for NULL immediately, and release what you already hold before returning an error.
  • Do not reuse one pointer variable for two unrelated blocks. Reassigning it before freeing the first block leaks the first one.
  • Test with a memory checker in development builds. The malloc article shows how to use AddressSanitizer for leaks and bad frees.

Frequently asked questions

What is dynamic memory allocation in C?
It is requesting a block of memory while the program runs, using functions from stdlib.h such as malloc, calloc and realloc, and giving it back with free. The block exists until you free it, regardless of which function created it, and its size can be decided at run time.
Which header declares malloc, calloc, realloc and free?
All four are declared in stdlib.h, so add #include <stdlib.h> before calling them.
Is dynamic memory allocation slower than using local variables?
Usually it costs more, because the allocator has to find a free block and keep records about it, while a local variable is set up when its block is entered. The C standard does not give timings, so measure your own program if the difference matters.
What happens if I forget to call free?
The block stays allocated until the process ends, which is a memory leak. The operating system reclaims the process's memory at exit, so a short tool may never show a problem, but a long-running program will keep using more memory.

Sources