C Programming Tutorial 0/65 lessons ~6 min read Lesson 39

    Dynamic Memory Allocation

    Dynamic memory allocation reserves memory at runtime on the heap using malloc, calloc, realloc, and releases it with free.

    Course progress0%
    Focus
    10 guided sections
    Practice signal
    Examples included
    Career prep
    Foundation builder

    Introduction

    Dynamic memory allocation reserves memory at runtime on the heap using malloc, calloc, realloc, and releases it with free.

    Understanding the topic

    malloc Allocate uninitialized bytes — check for NULL.

    calloc Allocate and zero-initialize.

    free Release memory — avoid double-free and use-after-free.

    • malloc — Allocate uninitialized bytes — check for NULL.
    • calloc — Allocate and zero-initialize.
    • free — Release memory — avoid double-free and use-after-free.

    Step-by-step explanation

    1. malloc — Allocate uninitialized bytes — check for NULL.
    2. calloc — Allocate and zero-initialize.
    3. free — Release memory — avoid double-free and use-after-free.

    Syntax reference

    Syntax reference:

    c
    ptr = malloc(n * sizeof(type));
    free(ptr);

    Informative example

    Example program:

    c
    #include <stdio.h>
    #include <stdlib.h>
    int main(void) {
    int *arr = malloc(5 * sizeof(int));
    if (!arr) return 1;
    for (int i = 0; i < 5; i++) arr[i] = i * 2;
    printf("%d\n", arr[4]);
    free(arr);
    return 0;
    }

    Output

    8

    Execution workflow

    1Dynamic Memory Allocation — step by step
    1 / 3

    malloc

    Allocate uninitialized bytes — check for NULL.

    Best practices

    • Enable warnings: gcc -Wall -Wextra -std=c11 source.c -o app
    • Give every variable a defined value before it is read.
    • Stay inside array bounds — C will not stop you from over-running a buffer.

    Common mistakes

    • Reading uninitialized storage — behavior is undefined.
    • Dismissing compiler warnings instead of fixing root causes.
    • Ignoring NULL returns from malloc, fopen, and similar APIs.

    Hands-on exercise

    Practice problems:

    • Dynamic array of n integers
    • Resize with realloc

    Summary

    Dynamic Memory Allocation in C — Heap APIs: malloc, calloc, realloc, free.

    Ready to mark this lesson complete?Track your journey across the entire course.