Coding/Learn/c/c dynamic memory allocation
C Foundational Course
01.Introduction, Compilation Pipeline & Syntax
02.Variables, Primitives & Explicit Type Casting
03.Operators, Precedence & Booleans (<stdbool.h>)
04.Control Flow: If-Else, Ternary & Switch
05.Loops (For, While, Do-While) & Jump Statements
06.Contiguous Arrays & Multi-Dimensional Matrices
07.Null-Terminated Strings & <string.h>
08.User Input, scanf & fgets Buffer Safety
09.Pointers, Memory Addresses & Dereferencing
10.Functions, Prototypes & Pass-by-Pointer
11.11. Recursion & High-Speed Function Pointers
12.File Streams: Create, Write & Read (fopen/fclose)
13.Structures, Unions & typedef Aliasing
14.Memory Word Alignment & Struct Padding
15.Enums & Bitwise Manipulation (Flags & Masks)
16.Dynamic Memory: malloc, calloc, realloc & free
17.Defensive Error Handling, errno & Assertions
18.Preprocessor Macros & Storage Classes
19.Fixed-Width Types (stdint.h), Math & Time (<time.h>)
20.Capstone: High-Performance In-Memory Key-Value Engine
Course Certificate0%

Complete all lessons to earn

LearnDynamic Memory: malloc, calloc, realloc & free
16 / 20 0%
Lesson 16 of 20
6 mins read

Dynamic Memory: malloc, calloc, realloc & free

PreviousNext Lesson
In Plain English

Heap memory allows requesting dynamic RAM buffers from the OS at runtime. malloc() allocates uninitialized memory, calloc() zero-initializes memory, realloc() resizes buffers dynamically, and free() releases heap blocks back to the OS.

The Mental Model

"Stack memory is reserving a table at a cafe that is cleared as soon as you leave; heap memory is renting a storage unit where you must explicitly return the physical key (free()) when finished."

Deep Dive: How It Works

Heap vs Stack: Stack is automatic and fast; heap is manual and dynamically sized.

realloc(): Expands or contracts existing buffers while preserving previous contents.

Dangling Pointers: Always set pointers to NULL after calling free(ptr).

Syntax Blueprint

int *buf = (int*)malloc(N * sizeof(int));
if (buf) {
    buf[0] = 42;
    free(buf);
    buf = NULL;
}

Allocate heap memory, check for non-NULL, use buffer, free memory, and set pointer to NULL.

PointCore Rules to Remember

Point star
The Golden Rule: Every malloc/calloc/realloc call must have a matching free() invocation.
Point star
NULL Check: malloc returns NULL if the host OS runs out of physical RAM.
Point star
Use-After-Free: Reading freed memory is undefined behavior; assign NULL immediately after freeing.

Common Beginner Traps & How to Fix Them

Mistake:Forgetting to free heap memory in error early-return branches.

Why it happens: Returning early skips the free() statement at the end of the function, creating persistent RAM leaks.

How to fix: Ensure every return pathway cleans up allocated resources.

Pro Tip: Prefer calloc(count, size) when initializing arrays of structs or pointers to guarantee clean zeroed memory.

Live Interactive Example

Hit Run Code to see it live
Dynamic Heap Array Allocation
C11 / GCC 9.2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Output Console
Click "Run Code" to view the rendered output.
How it works: malloc allocates 12 bytes on the heap and free releases the memory back to the OS.

Your Turn: Micro Challenge

No pressure! Edit the starter code below and test your solution with instant feedback.

Micro Exercise

Confirm Clean Heap Teardown

  • PointPrint "Memory Freed: SUCCESS\n" after freeing the array.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Sandbox Output
Click "Run & Check" to test your solution.

Finished reading and practicing?

Mark this lesson as completed to update your course progress.

PreviousNext Lesson
Overview100 SheetLearnCertificates