C Memory Management

So far, C has handled memory for you automatically. In this lesson you will meet dynamic memory management, which lets your program ask for exactly as much memory as it needs while it is running.

Every variable you create needs space in the computer's memory. Most of the time, C reserves this space for you automatically when you declare a variable, and frees it when the variable goes out of scope. This is called automatic memory management, and it is easy but not always flexible enough.

Why We Need Dynamic Memory

Sometimes you do not know how much memory you will need until the program is already running. For example, you might ask the user how many numbers they want to store. Dynamic memory management lets you request memory at that moment, in the exact amount you need, instead of guessing a fixed size ahead of time.

  • malloc() - asks for a block of memory of a given size.
  • calloc() - asks for memory and also sets every byte to zero.
  • realloc() - changes the size of memory you already asked for.
  • free() - gives memory back to the system when you are finished with it.

These four functions all live in the standard library, so you must include <stdlib.h> at the top of any program that uses them. This header also gives you the special value NULL, which these functions return when they cannot find enough memory.

A first look at dynamic memory

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

int main() {
    // Ask for enough memory to hold one int
    int *ptr = malloc(sizeof(int));

    if (ptr == NULL) {
        printf("Memory request failed.\n");
        return 1;
    }

    *ptr = 42;                 // store a value in that memory
    printf("Value: %d\n", *ptr);

    free(ptr);                 // give the memory back
    return 0;
}

The Stack and the Heap

Automatic variables live in an area of memory called the stack, which is managed for you. Memory you request with malloc() comes from a different area called the heap. Heap memory stays reserved until you free it yourself, which gives you control but also responsibility.

Note: With great power comes great responsibility. Every block of memory you take from the heap must be handed back with free(). If you forget, your program keeps holding memory it no longer uses, a problem called a memory leak.
FunctionWhat it doesHeader
malloc()Reserve a block of memory<stdlib.h>
calloc()Reserve memory and zero it<stdlib.h>
free()Release memory back to the system<stdlib.h>

Exercise: C Memory Management

What values does memory returned by `malloc()` contain?