Loading...

C essentialsPointers & Memory

Dynamic memory: malloc, calloc, realloc & free

15 min lesson

Next
  • Dynamic memory is memory you request at runtime with functions like malloc, calloc and realloc, and release with free.
  • It matters because sometimes you do not know the size you need until the program runs, like reading a list of unknown length.
  • Think of the heap as a big storeroom where you rent boxes. malloc rents one box, calloc rents a box and cleans it, realloc resizes your rental, and free returns the key.
  • malloc(size) returns a pointer to a block of at least size bytes, or NULL if it fails. The bytes are uninitialized.
  • calloc(count, size) returns a block for count items of size bytes each, and zeroes every byte.
  • realloc(ptr, newSize) resizes a block, possibly moving it, and returns the new pointer or NULL on failure.
  • free(ptr) returns the block to the system; using the pointer after free is a bug, and free(NULL) is safe.
  • The computer tracks allocated blocks in a heap manager; malloc finds a free block of the requested size, and free marks it available again.
  • The syntax is: int *p = malloc(n * sizeof *p); and free(p);.
  • A realistic use: growing an array as the user adds items, or allocating a buffer sized from a file length.
  • A surprising detail: realloc can move the block, so you must update your pointer with its return value, and never lose the original pointer on failure.
  • The example program allocates an array with calloc, fills it, grows it with realloc, prints the values and frees the memory.
Keep in mind
  • Always check the result of malloc, calloc and realloc for NULL.
  • Free every block exactly once and set the pointer to NULL afterward.
  • Use realloc through a temporary pointer so you do not leak on failure.
  • Remember that malloc does not zero memory; calloc does.
  • You now control memory directly. This is a big milestone!
main.c
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    // Ask for space for 3 ints; calloc zeroes them
    int count = 3;
    int *values = calloc((size_t)count, sizeof *values);
    // Always check that allocation succeeded
    if (values == NULL) {
        return 1;
    }

    // Fill the first three slots
    for (int i = 0; i < count; i++) {
        values[i] = (i + 1) * 10;
    }

    // Grow the block to hold 5 ints using a temporary pointer
    int newCount = 5;
    int *grown = realloc(values, (size_t)newCount * sizeof *values);
    // If realloc fails, keep the original block and exit
    if (grown == NULL) {
        free(values);
        return 1;
    }
    // Use the new pointer from now on
    values = grown;

    // Fill the two new slots
    values[3] = 40;
    values[4] = 50;

    // Print all values
    for (int i = 0; i < newCount; i++) {
        printf("values[%d] = %d\n", i, values[i]);
    }

    // Release the heap block when done
    free(values);
    // Set the pointer to NULL so it cannot be used by accident
    values = NULL;

    return 0;
}

What happens: values[0] = 10 values[1] = 20 values[2] = 30 values[3] = 40 values[4] = 50

Breaking it down

calloc call

calloc((size_t)count, sizeof *values)

Requests space for count items, each sizeof(int) bytes, and zeroes every byte. Returns NULL on failure.

Filling values

values[i] = (i + 1) * 10;

Writes to the allocated block. The index must stay within the allocated count or you overflow the block.

realloc via temp

int *grown = realloc(values, ...)

Asks for a larger block. Using a temporary pointer preserves the original if realloc returns NULL, avoiding a leak.

Updating the pointer

values = grown;

realloc may move the block, so the old pointer is no longer valid. Update it with the new address.

free and NULL

free(values); values = NULL;

Returns the block and clears the pointer so a later accidental use is caught instead of silently corrupting memory.

Dynamic memory functions

FunctionPurposeZeroed?Notes
malloc(n)Allocate n bytesNoCheck for NULL
calloc(c, s)Allocate c*s bytesYesGood for arrays
realloc(p, n)Resize blockNew bytes not zeroedMay move block
free(p)Release blockN/Afree(NULL) is safe

A helpful analogy

Dynamic memory is like renting storage boxes. malloc rents a box of the size you ask for; calloc rents a box and cleans it before handing it over; realloc changes the size of your rental, sometimes moving you to a different box; free returns the key so someone else can use the box.

Nesting rules

  • 1.Always check the pointer returned by malloc, calloc and realloc for NULL before using it.
  • 2.Call free exactly once per allocated block, and set the pointer to NULL after.
  • 3.Use a temporary pointer with realloc so a failure does not leak the original block.
  • 4.Never read or write past the allocated size; there is no bounds checking.

Common mistakes

Losing the original pointer on realloc failure

Avoid

p = realloc(p, n); // leaks on failure

Use instead

int *tmp = realloc(p, n); if (!tmp) { free(p); return 1; } p = tmp;

If realloc returns NULL, the original block is still allocated but p has been overwritten with NULL, so the block leaks.

Using memory after free

Avoid

free(p); printf("%d", *p); // use-after-free

Use instead

free(p); p = NULL;

After free the block belongs to the system and may be reused. Reading it gives garbage or crashes. Set p to NULL to catch mistakes.

Forgetting to multiply by the element size

Avoid

int *p = malloc(10); // 10 bytes, not 10 ints

Use instead

int *p = malloc(10 * sizeof *p);

malloc takes bytes, not elements. Multiplying by sizeof *p gives the correct total for 10 ints.

Quick tips

  • •Write malloc(n * sizeof *p) so the size follows the pointer type automatically.
  • •Use calloc when you need the memory zeroed; it saves a loop.
  • •Test your program with valgrind or -fsanitize=address to catch leaks and overflows.
  • •Try running the example with a smaller initial count and growing it more than once.
  • •Free memory on every return path, including error paths.
Previous
Next