Thuta Learning
C
AdvancedProgrammingBeginner

Dynamic Memory

CLesson 2730 min

What you'll walk away with

  • Call malloc and calloc in the count * sizeof *p form and check the result for NULL
  • Grow an array safely with realloc and a temporary pointer
  • Free each block exactly once and reset the pointer to NULL
  • Explain what a memory leak, a use-after-free and a double free are

Explain it simply

Explain it simply

Every variable and array you have written so far had its size fixed before the program was compiled, and it vanished automatically when its function ended. Dynamic memory is like renting space in a storage warehouse: while the program runs you ask for exactly as much as you need, and it stays yours until you hand it back.

The warehouse can run out of space, so a request may be refused and you must always check the answer. Forget to hand the space back and it stays taken until the program ends; walk back into space you already returned and you may be touching someone else's belongings.

Problem → Why → Solution

The problem: a fixed array cannot follow the user's count

You want a function that builds the first n square numbers, where n is typed in by the user. With only fixed-size arrays you are stuck twice. A local array of 100 elements overflows when the user types 500 and wastes memory when they type 3. Worse, returning that local array hands the caller a dangling pointer, and GCC warns that the function returns address of local variable.

squares.c
#include <stdio.h>

int *make_squares(int n) {
    int result[100];               /* too small for n > 100 */
    for (int i = 0; i < n; i++) {
        result[i] = i * i;
    }
    return result;                 /* result dies when the function returns */
}

int main(void) {
    int n = 0;
    printf("How many squares? ");
    if (scanf("%d", &n) != 1) return 1;
    int *squares = make_squares(n);
    printf("%d\n", squares[n - 1]);  /* undefined behaviour */
    return 0;
}

Why isn't stack memory enough?

Local arrays live in the function's stack frame, whose size is fixed at compile time and which disappears when the function returns. What you need is memory whose size you choose at run time and whose lifetime you control: it should exist until you explicitly say you are done. That is exactly what the heap provides through malloc(), calloc(), realloc() and free().

Core concept: request, check, use, release

Dynamic memory comes from the heap, a pool of memory the C library manages for you. malloc(bytes) reserves a block of at least that many bytes and returns a void * to its first byte. A void * converts automatically to any object pointer such as int *, so C needs no cast. The contents of a fresh malloc block are indeterminate, so reading them before writing is a bug. calloc(count, size) reserves count elements of size bytes each and sets every byte to zero, which gives 0 for integers.

Every allocation can fail, and failure is reported by returning NULL, so check the result before using it, every time. Write the size as count * sizeof *ptr: sizeof *ptr is the size of whatever ptr points to, it is computed at compile time without dereferencing anything, and it stays correct if you later change the element type. When count comes from outside the program, guard the multiplication with if (count > SIZE_MAX / sizeof *ptr) so that a huge count cannot wrap around to a small size.

realloc(ptr, new_bytes) resizes a block. It may grow the block in place, or allocate a new one, copy the old contents and free the old block, so the address can change. If it fails it returns NULL and leaves the old block untouched, which is why you assign the result to a temporary pointer first: writing ptr = realloc(ptr, n) would lose your only pointer to the still-allocated block on failure, a guaranteed leak.

free(ptr) gives the block back. Every successful allocation needs exactly one free, done by whichever part of the program owns the block. After free, the pointer still holds the old address but must not be used: reading or writing through it (use-after-free) or freeing it again (double free) is undefined behaviour. Setting the pointer to NULL right after free turns accidental reuse into an obvious bug, and the standard defines free(NULL) to do nothing.

text
int *values = calloc(5, sizeof *values);
----------------------------------------
  stack (main's frame)              heap
 +---------------------+       +----+----+----+----+----+
 | count  = 5          |       |  0 | 10 | 20 | 30 | 40 |
 | values = -----------+-----> +----+----+----+----+----+
 +---------------------+        5 * sizeof(int) = 20 bytes
  released automatically        lives until free(values)
  when main returns
Mental model: borrowing from the heap
  1. Ask: p = malloc(n * sizeof *p)
  2. Check: if (p == NULL) handle it
  3. Use p like an array of n items
  4. Return it: free(p); p = NULL;

One allocation, one owner, one free: decide who frees a block at the moment you allocate it.

General pattern

c
type *p = malloc(count * sizeof *p);      /* uninitialized block */
type *z = calloc(count, sizeof *z);       /* zero-filled block */
if (p == NULL) { /* handle the failure */ }

type *tmp = realloc(p, new_count * sizeof *p);
if (tmp != NULL) p = tmp;                 /* on failure p is still valid */

free(p);
p = NULL;

Always compute sizes as element count times sizeof *p. Check for NULL after every allocation, send realloc's result to a temporary pointer first, and set the pointer to NULL right after free.

Example: allocating an int array at run time

The program asks the heap for room for five ints, fills and prints them, and gives the memory back. Here count is a plain variable, but it could just as well come from user input or a file, which is the whole point: the size is decided while the program runs. The output is 0 10 20 30 40.

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

int main(void) {
    size_t count = 5;
    int *values = calloc(count, sizeof *values);
    if (values == NULL) return EXIT_FAILURE;

    for (size_t i = 0; i < count; ++i) values[i] = (int)(i * 10);
    for (size_t i = 0; i < count; ++i) printf("%d%c", values[i], i + 1 == count ? '\n' : ' ');

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

Code breakdown

  1. Line 6calloc(count, sizeof *values)

    calloc takes the count and the element size separately, does the multiplication itself and zeroes every byte. Mainstream C libraries return NULL rather than a too-small block when that product would overflow.

  2. Line 6sizeof *values

    This is the size of what values points to, an int. sizeof does not evaluate its operand, so using it before values is assigned is safe, and it stays correct if the type later changes to double.

  3. Line 7if (values == NULL) return EXIT_FAILURE;

    If the allocation failed, the program stops at once instead of indexing NULL. EXIT_FAILURE is the portable exit code from stdlib.h.

  4. Line 9values[i] = (int)(i * 10);

    The heap block is indexed exactly like an ordinary array. i is a size_t, so the (int) cast makes the conversion explicit.

  5. Lines 12-13free(values);

    The block is released exactly once, and the next line sets values = NULL, so any accidental later use finds NULL rather than a freed address.

You should see
0 10 20 30 40

Growing an array with realloc

A common pattern is a dynamic array that starts small and doubles its capacity whenever it fills up. Doubling keeps the number of realloc calls small: storing a million items needs only about twenty resizes. Notice how bigger receives the result and items is replaced only once the call has succeeded.

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

int main(void) {
    size_t capacity = 2, length = 0;
    int *items = malloc(capacity * sizeof *items);
    if (items == NULL) return EXIT_FAILURE;

    for (int value = 1; value <= 5; value++) {
        if (length == capacity) {
            size_t new_capacity = capacity * 2;
            int *bigger = realloc(items, new_capacity * sizeof *items);
            if (bigger == NULL) {        /* items is still valid here */
                free(items);
                return EXIT_FAILURE;
            }
            items = bigger;
            capacity = new_capacity;
            printf("grew to %zu slots\n", capacity);
        }
        items[length++] = value * value;
    }

    for (size_t i = 0; i < length; i++) printf("%d ", items[i]);
    printf("\n");
    free(items);
    items = NULL;
    return EXIT_SUCCESS;
}

The program prints grew to 4 slots, grew to 8 slots and then 1 4 9 16 25. Had realloc failed halfway, items would still point to the old, valid block, so the error path can free it cleanly instead of leaking it.

malloc, calloc and realloc compared

FunctionWhat you getUse it when
malloc(bytes)A block of that many bytes, contents indeterminateYou will write every element straight away
calloc(count, size)count * size bytes, all zero; the library does the multiplicationYou want zeros, or count comes from input
realloc(p, bytes)The block resized, possibly at a new address, old contents keptAn existing buffer must grow or shrink

Avoid asking for zero bytes

What malloc(0) returns is implementation-defined, and realloc(p, 0) behaves differently across C libraries (C23 even makes it undefined behaviour). Handle a possible size of 0 yourself before calling the allocator.

In real projects

Where this shows up in real projects

Anything whose size is unknown until run time lives on the heap: the lines of a file being edited, records loaded from a database, an image decoded from disk, the nodes of a linked list. Long-running programs such as servers allocate and free memory for every request, so a leak of a few bytes per request slowly grows until the process has to be killed.

Real codebases make ownership explicit. A function that returns allocated memory documents that the caller must free it (strdup() and getline() on POSIX systems are standard examples), and a larger component usually pairs a create function with a matching destroy function. Teams run their tests under AddressSanitizer or Valgrind to catch leaks, use-after-free and double free, because these bugs often produce correct-looking output until the day they corrupt data.

Common mistakes

Common mistakes

1. Assigning realloc straight back to the same pointer

data = realloc(data, n * sizeof *data); looks tidy, but when realloc fails it returns NULL, overwrites your only copy of the address and leaks the old block. Use a temporary pointer and replace data only on success.

2. Using memory after free()

After free(values); the pointer still holds the old address, so values[0] may even print the old number for a while. That is use-after-free, undefined behaviour that can corrupt the heap later on. Set the pointer to NULL straight after freeing, and free each block exactly once.

3. Forgetting the element size

malloc(count) reserves count bytes, not count ints, so writing count ints overruns the block fourfold. Always multiply by sizeof *p, and never write sizeof(p): that is the size of the pointer itself, 8 bytes, not of what it points to.

4. Skipping the NULL check

Small allocations rarely fail on a desktop, so a missing check goes unnoticed until the program runs on a busy server or an embedded device. Check every result and decide what to do: return an error code, print a message or exit cleanly.

Best practices

Best practices

  • Write allocations as p = malloc(count * sizeof *p) and check for NULL on the very next line.
  • Decide who owns each block when you allocate it, and document functions that return memory the caller must free.
  • While testing, build with -fsanitize=address or run the program under Valgrind.

Mini challenge

Mini challenge: duplicate and append

Write one function that copies an int array into heap memory and one that appends an element to it, then release the memory correctly.

  • int *duplicate(const int *src, size_t count) returns a new heap copy, or NULL when src is NULL, count is 0 or the allocation fails
  • Guard the byte count against overflow with SIZE_MAX / sizeof *src
  • int *append(int *arr, size_t count, int value) uses realloc with a temporary pointer and returns NULL on failure, leaving arr untouched
  • main prints the copy, appends 16 and 23, shows the source array is unchanged, then frees the copy and sets the pointer to NULL
grow_copy.c
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* Returns a heap copy of src, or NULL. The caller must free() it. */
int *duplicate(const int *src, size_t count) {
    // TODO: reject NULL, count == 0 and counts whose byte size would overflow
    // TODO: malloc the copy, check it, copy the data with memcpy, return it
}

/* Grows arr by one slot. On failure returns NULL and arr is untouched. */
int *append(int *arr, size_t count, int value) {
    // TODO: realloc into a temporary pointer, then store value in the new slot
}

int main(void) {
    int original[] = {4, 8, 15};
    // TODO: duplicate, print, append 16 and 23, print, print the original,
    //       then free the copy and set it to NULL
    return 0;
}

Expected: The output should be: copy: 4 8 15 after append: 4 8 15 16 23 original: 4 8 15 duplicate(NULL, 3) returns NULL

Show hint

memcpy(copy, src, count * sizeof *copy) copies all the bytes in one call. In append(), store realloc(arr, (count + 1) * sizeof *arr) in an int *bigger and write bigger[count] = value; only when it is not NULL. In main, replace copy with append's result only when that result is not NULL.

Show solution
grow_copy.c
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* Returns a heap copy of src, or NULL. The caller must free() it. */
int *duplicate(const int *src, size_t count) {
    if (src == NULL || count == 0 || count > SIZE_MAX / sizeof *src) {
        return NULL;
    }
    int *copy = malloc(count * sizeof *copy);
    if (copy == NULL) {
        return NULL;
    }
    memcpy(copy, src, count * sizeof *copy);
    return copy;
}

/* Grows arr by one slot. On failure returns NULL and arr is untouched. */
int *append(int *arr, size_t count, int value) {
    if (count >= SIZE_MAX / sizeof *arr) {
        return NULL;
    }
    int *bigger = realloc(arr, (count + 1) * sizeof *bigger);
    if (bigger == NULL) {
        return NULL;
    }
    bigger[count] = value;
    return bigger;
}

static void print_all(const char *label, const int *values, size_t count) {
    printf("%s:", label);
    for (size_t i = 0; i < count; i++) {
        printf(" %d", values[i]);
    }
    printf("\n");
}

int main(void) {
    int original[] = {4, 8, 15};
    size_t count = 3;

    int *copy = duplicate(original, count);
    if (copy == NULL) {
        return EXIT_FAILURE;
    }
    print_all("copy", copy, count);

    int extra[] = {16, 23};
    for (size_t i = 0; i < 2; i++) {
        int *grown = append(copy, count, extra[i]);
        if (grown == NULL) {
            free(copy);
            return EXIT_FAILURE;
        }
        copy = grown;
        count++;
    }
    print_all("after append", copy, count);
    print_all("original", original, 3);

    free(copy);
    copy = NULL;

    int *none = duplicate(NULL, 3);
    printf("duplicate(NULL, 3) returns %s\n", none == NULL ? "NULL" : "memory");
    free(none);                    /* free(NULL) is allowed and does nothing */
    return EXIT_SUCCESS;
}

Quick quiz 1 / 3

Which code grows the array p to n elements safely?

Quick quiz 2 / 3

What does calloc(5, sizeof(int)) give you that malloc(5 * sizeof(int)) does not?

Quick quiz 3 / 3

int *p = malloc(sizeof *p); ... free(p); p = NULL; free(p); — what happens at the second free?

What to remember

  • malloc, calloc and realloc give you heap memory whose size is chosen at run time and whose lifetime you control.
  • Check every allocation for NULL and size it with count * sizeof *p.
  • Send realloc's result to a temporary pointer; on failure the old block is still valid.
  • Free each block exactly once and then set the pointer to NULL; using freed memory is undefined behaviour.

SEI CERT C Coding Standard — Carnegie Mellon SEI

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.