0
0
CConceptBeginner · 3 min read

Dynamic Memory Allocation in C: What It Is and How It Works

In C, dynamic memory allocation is the process of requesting memory from the system during program execution using functions like malloc and free. It allows programs to use memory flexibly, allocating and freeing space as needed instead of fixed sizes at compile time.
⚙️

How It Works

Dynamic memory allocation in C works like renting space in a warehouse only when you need it, instead of buying a fixed-size warehouse upfront. When your program runs, it can ask the system for a block of memory of a certain size. This memory is taken from a pool called the heap.

Once you finish using that memory, you return it to the system so others can use it. This process is managed by functions such as malloc to allocate and free to release memory. This flexibility helps programs handle data whose size is not known before running, like user input or growing lists.

💻

Example

This example shows how to allocate memory for an integer array dynamically, assign values, print them, and then free the memory.

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

int main() {
    int n = 5;
    int *arr = malloc(n * sizeof(int));
    if (arr == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }

    for (int i = 0; i < n; i++) {
        arr[i] = (i + 1) * 10;
    }

    printf("Array elements: ");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");

    free(arr);
    return 0;
}
Output
Array elements: 10 20 30 40 50
🎯

When to Use

Use dynamic memory allocation when you don't know the amount of data your program will need in advance. For example, reading a list of user inputs where the number of inputs varies, or creating data structures like linked lists and trees that grow or shrink during execution.

It helps save memory by allocating only what is needed and releasing it when done, making programs more efficient and flexible.

Key Points

  • Dynamic memory is allocated from the heap during program run time.
  • malloc allocates memory, and free releases it.
  • Always check if allocation succeeded to avoid errors.
  • Freeing memory prevents memory leaks and keeps programs efficient.

Key Takeaways

Dynamic memory allocation lets C programs request memory while running, not just before.
Use malloc to allocate and free to release memory safely.
Always check if memory allocation was successful before using the memory.
Dynamic allocation is useful for flexible data sizes like user input or growing lists.