Course contentsShow
← C
Lesson 868 of 1,21912. The Standard LibraryFree lesson

Allocating memory with `malloc` and `free`

Allocating memory with malloc and free

What you'll learn: How to request a specific amount of memory from the computer while your program is running and return it when you are finished.

The "Hotel Room" Analogy

Up until now, you have used variables like int x or char name[20]. These are like reserved seats at a theater; the size is fixed before the show starts. But what if you don't know how much data you will have until the program is actually running?

Think of Dynamic Memory Allocation like renting a hotel room. You don't live there permanently. You ask the front desk for a room of a certain size, you use it for a while, and then you must "check out" so someone else can use the space. In C, the "front desk" is a function called malloc, and "checking out" is a function called free.

Using malloc

The malloc function stands for "memory allocation." It asks the computer to set aside a block of bytes in a region called the heap. To use it, you tell it exactly how many bytes you want. Since different data types have different sizes on different computers, we use the sizeof operator to be safe.

#include <stdio.h>
#include <stdlib.h> // Required for malloc and free

int main() {
    int *ptr;
    int numberOfElements = 5;

    // Request space for 5 integers
    ptr = (int*)malloc(numberOfElements * sizeof(int));

    // Check if memory was successfully granted
    if (ptr == NULL) {
        printf("Memory not allocated. System is full!\n");
        return 1;
    }

    // Use the memory just like an array
    for (int i = 0; i < numberOfElements; i++) {
        ptr[i] = i * 10;
        printf("%d ", ptr[i]);
    }

    // ALWAYS release the memory when done
    free(ptr);

    return 0;
}

The importance of free

Unlike variables declared inside functions, memory requested with malloc does not disappear automatically. If you keep asking for "hotel rooms" and never check out, your computer will eventually run out of memory. This is called a memory leak.

Whenever you use malloc, you must eventually call free(ptr). This tells the system: "I'm done with this block of memory; you can give it to someone else."

Key takeaway

Use malloc to grab a specific amount of memory at runtime, and always use free to release it when you are finished to prevent memory leaks.