C: Dynamic Memory Management

🗓 Last updated: 2026-11-30👤 Written by: Gray✓ Reviewed by: Dana🏷 Category: C Tutorial

Dynamic memory is like renting an apartment — you apply when you need it (malloc), and you move out when you're done (free). If you never move out, you keep hogging resources — that's a memory leak.

Reference entries in this section: malloc free calloc realloc

1. Why Dynamic Memory

Local variables on the stack disappear when a function returns, and array sizes must be determined at compile time. When the data size is only known at runtime, or you need data to persist across function calls, you need dynamic memory on the heap.

C
// Variable declaration
int n;
// I/O operation
scanf("%d", &n);
int arr[n];
⚠️ Note: Variable-length arrays (VLA) are a C99 feature not supported by all compilers, and are not recommended for large arrays. The proper approach is to use malloc.


2. malloc and free

malloc allocates a specified number of bytes on the heap and returns void *. You must free the memory when done.

C
// Variable declaration
int *p = (int *)malloc(sizeof(int) * 5);
// Conditional check
if (p == NULL) {
    // I/O operation
    printf("Memory allocation failed\n");
    // Return result
    return 1;
}
// For loop
for (int i = 0; i < 5; i++) {
    p[i] = i * 10;
}
// For loop
for (int i = 0; i < 5; i++) {
    // I/O operation
    printf("%d ", p[i]);
}
// Dynamic memory operation
free(p);
p = NULL;
TEXT
0 10 20 30 40
💡 Tip: malloc does not initialize memory — the contents are garbage values. Always check the return value for NULL after allocation. Setting the pointer to NULL after free is good practice to prevent dangling pointers.


3. calloc

calloc allocates memory and initializes every bit to 0. Its parameters are the number of elements and the size of each element.

TEXT
int *p = (int *)calloc(5, sizeof(int));
if (p) {
    for (int i = 0; i < 5; i++) {
        printf("%d ", p[i]);
    }
    free(p);
}
TEXT
0 0 0 0 0

malloc vs calloc:

Function Initialization Parameters
malloc No initialization Total bytes
calloc Zeroed Element count, size of each element

4. realloc

realloc resizes previously allocated memory — it can expand or shrink.

C
// Variable declaration
int *p = (int *)malloc(sizeof(int) * 3);
p[0] = 10; p[1] = 20; p[2] = 30;

// Variable declaration
int *tmp = (int *)realloc(p, sizeof(int) * 5);
// Conditional check
if (tmp) {
    p = tmp;
    p[3] = 40;
    p[4] = 50;
    // For loop
    for (int i = 0; i < 5; i++) {
        // I/O operation
        printf("%d ", p[i]);
    }
    // Dynamic memory operation
    free(p);
}
TEXT
10 20 30 40 50
⚠️ Note: realloc may return a new address (original data is automatically copied) or the same address. Never write p = realloc(p, ...) — if it fails and returns NULL, the original pointer is lost. Use a temporary variable to receive the result.


5. Dynamic 1D Array

▶ Example

▶ Try it Yourself
TEXT
Enter number of elements: 5
1 4 9 16 25

6. Dynamic 2D Array

There are two common approaches to implementing dynamic 2D arrays.

(1) Approach 1: Pointer Array (Each Row Allocated Independently)

C
// Variable declaration
int rows = 3, cols = 4;
int **matrix = (int **)malloc(sizeof(int *) * rows);
// For loop
for (int i = 0; i < rows; i++) {
    matrix[i] = (int *)calloc(cols, sizeof(int));
}

matrix[1][2] = 99;
// I/O operation
printf("%d\n", matrix[1][2]);

// For loop
for (int i = 0; i < rows; i++) {
    // Dynamic memory operation
    free(matrix[i]);
}
// Dynamic memory operation
free(matrix);
TEXT
99

(2) Approach 2: Contiguous Memory (Single Allocation)

TEXT
int rows = 3, cols = 4;
int *buf = (int *)calloc(rows * cols, sizeof(int));
int **matrix = (int **)malloc(sizeof(int *) * rows);
for (int i = 0; i < rows; i++) {
    matrix[i] = buf + i * cols;
}

matrix[2][3] = 77;
printf("%d\n", matrix[2][3]);

free(matrix);
free(buf);
TEXT
77
💡 Tip: Approach 2 has contiguous memory, which is cache-friendly and simpler to free. Approach 1 allows each row to have a different number of columns (jagged array).

▶ Example

▶ Try it Yourself
TEXT
  1  2  3  4
  5  6  7  8
  9 10 11 12

7. Common Dynamic Memory Errors

(1) Forgetting to free — Memory Leak

C
// Function definition
void leak(void) {
    // Variable declaration
    int *p = (int *)malloc(sizeof(int) * 100);
}

When the function ends, the local variable p is gone, but the 100 ints of heap memory are still occupied and can never be freed.

(2) Double free

C
// Variable declaration
int *p = (int *)malloc(sizeof(int));
// Dynamic memory operation
free(p);
// Dynamic memory operation
free(p);
⚠️ Note: Calling free on the same memory twice is undefined behavior and may crash the program. Set the pointer to NULL immediately after free — calling free(NULL) is safe.

(3) Using Freed Memory

TEXT
int *p = (int *)malloc(sizeof(int));
*p = 42;
free(p);
printf("%d\n", *p);
⚠️ Note: Accessing memory after freeing it is a dangling pointer — the results are unpredictable.

(4) Out-of-Bounds Access

C
// Variable declaration
int *p = (int *)malloc(sizeof(int) * 5);
p[5] = 100;

5 elements were allocated with indices 0-4, so p[5] is out of bounds.


8. valgrind Introduction

Valgrind is a memory-checking tool on Linux that can detect memory leaks, out-of-bounds access, and uninitialized reads.

BASH
gcc -g -o myapp myapp.c
valgrind --leak-check=full ./myapp

Typical output:

TEXT
==12345== HEAP SUMMARY:
==12345==     in use at exit: 400 bytes in 1 blocks
==12345==   total heap usage: 2 allocs, 1 frees, 800 bytes allocated
==12345==
==12345== 400 bytes in 1 blocks are definitely lost in loss record 1 of 1
==12345==    at 0x4C2FB0F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==12345==    by 0x10915E: leak (myapp.c:5)
💡 Tip: On Windows you can use Dr. Memory or Visual Studio's debug heap. On macOS, use Instruments' Leaks tool.

▶ Example 3: Dynamically Grow an Array with realloc

▶ Try it Yourself

输出:

TEXT
10 20 30 40 50

Reference entries in this section: malloc free calloc realloc

❓ FAQ

Q Difference between malloc and calloc?
A malloc(bytes) allocates uninitialized memory — the contents are whatever was left there before. calloc(n, element_size) allocates n times element_size bytes and zeroes every byte. calloc is slightly slower but perfect for struct arrays or anything that depends on zero initialization.
Q What really happens when you don't free after malloc before program termination?
A Modern operating systems reclaim all process memory on termination, so the leak is gone at the OS level. However, long-running programs (servers, daemons) will accumulate leaks over time until they run out of address space. Valgrind or AddressSanitizer will still report it as a bug.
Q How does free know how much to free?
A malloc stores metadata before the returned pointer — typically the size as a size_t. free reads this value to know how many bytes to release. That is why passing a pointer you did not get from malloc/calloc/realloc to free is undefined behavior — it corrupts the metadata.
Q Will free(NULL) crash?
A No. The C standard guarantees that free(NULL) is safe and does nothing. So there is no need to check whether a pointer is NULL before calling free. You do need to set it to NULL after freeing though — double-free corrupts the heap.
Q What does malloc return if it fails?
A NULL. Always check the return value of malloc before dereferencing it. On a 64-bit system, a large contiguous allocation may fail even when total free memory is sufficient (heap fragmentation). Use errno after malloc to get the reason.
Q What is a segmentation fault?
A A segfault happens when your program reads or writes memory it is not allowed to touch. In dynamic memory code this usually means dereferencing NULL, going out of bounds on a heap array, or using a pointer to freed memory (use-after-free). Run with AddressSanitizer to find the exact line.
Q What are the dangers of using pragma once?
A pragma once is a non-standard preprocessor directive that some compilers (GCC, Clang, MSVC) accept, but it is not part of the C standard. It can fail with unusual file paths (case-sensitive filesystems, symlinks) and slows compilation because the compiler must open and stat the file. Use traditional include guards for portability.
Q What is array-to-pointer conversion aka. decay?
A When you pass an array as a function argument, it automatically becomes a pointer to its first element. That is why sizeof inside a function returns 8 (pointer size) instead of the array size. This rule is fundamental to how pointers and arrays interact in C.

📖 Summary

📝 Exercises

  1. Write a program: the user inputs n, dynamically allocate n ints, read n numbers, sort and output them, then free the memory
  2. Write dynamic 2D array functions: int **create_matrix(int rows, int cols) and void free_matrix(int **m, int rows). In main, create a 4x5 matrix, assign values, and print
  3. Intentionally create a memory leak in your code, then use valgrind (or Dr. Memory) to detect it and examine the output
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏