Skip to main content
C Programming Basics
CHAPTER 14 Beginner

Dynamic Memory Allocation

Updated: May 17, 2026
5 min read

# CHAPTER 14

Dynamic Memory Allocation

1. Introduction

When you declare an array like int arr[100];, the size is fixed at compile time. What if you don't know how much data the user will enter? If they enter 150 items, your program crashes. If they enter 2 items, you've wasted 98 slots. Dynamic Memory Allocation allows you to request memory from the OS *while the program is running*.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Understand the difference between the Stack and the Heap.
  • Use malloc() and calloc() to request memory.
  • Use realloc() to resize memory.
  • Use free() to prevent memory leaks.
  • Build a dynamically sized application.

3. Stack vs. Heap Memory

  • Stack: Fast, auto-managed memory where local variables and arrays live. It is small (a few megabytes).
  • Heap: Large pool of memory used for dynamic allocation. You (the programmer) must manually request and release memory here.

4. The <stdlib.h> Library

To use dynamic memory functions, you MUST include <stdlib.h>.

#### 1. malloc() - Memory Allocation Requests a single block of memory of a specific size. It returns a void pointer to the first byte, which you cast to your desired type. It does NOT initialize the memory (contains garbage values).

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

int main() {
    int *ptr;
    // Request memory for 5 integers
    ptr = (int*) malloc(5 * sizeof(int)); 
    
    if (ptr == NULL) {
        printf("Memory allocation failed!\n");
        return 1;
    }
    
    ptr[0] = 10; // Use it just like an array!
    printf("%d\n", ptr[0]);
    
    free(ptr); // ALWAYS free memory when done!
    return 0;
}

#### 2. calloc() - Contiguous Allocation Similar to malloc, but it takes two arguments (number of elements, size of element) and initializes all bits to zero.

c
123
int *ptr;
// Allocate 5 integers and set them all to 0
ptr = (int*) calloc(5, sizeof(int)); 

#### 3. realloc() - Re-allocation Resizes a previously allocated memory block. Useful if your array gets full and you need more space.

c
12
// Resize ptr to hold 10 integers instead of 5
ptr = (int*) realloc(ptr, 10 * sizeof(int));

#### 4. free() - Releasing Memory C has no Garbage Collector. If you malloc memory, it stays reserved until the program ends. If you do this in a loop, you will use all available RAM (a Memory Leak). You must call free().

c
12
free(ptr);
ptr = NULL; // Good practice: prevent Dangling Pointers

5. Mini Project: Dynamic Student Records

Let's ask the user how many students they have, create an array of that exact size, and calculate the average.
c
12345678910111213141516171819202122232425262728293031323334
#include <stdio.h>
#include <stdlib.h>

int main() {
    int n, i;
    int *marks;
    int sum = 0;

    printf("Enter number of students: ");
    scanf("%d", &n);

    // Dynamically allocate memory
    marks = (int*) malloc(n * sizeof(int));

    if (marks == NULL) {
        printf("Memory allocation failed!\n");
        return 1;
    }

    // Get input
    for (i = 0; i < n; i++) {
        printf("Enter marks for student %d: ", i + 1);
        scanf("%d", &marks[i]);
        sum += marks[i];
    }

    printf("Average marks: %.2f\n", (float)sum / n);

    // Free memory
    free(marks);
    printf("Memory freed successfully.\n");

    return 0;
}

6. Visualizing the Heap

1234567
int *ptr = malloc(3 * sizeof(int));

Stack:               Heap (Dynamically Allocated):
+----------+         +--------+--------+--------+
| ptr      | ------> | Garbage| Garbage| Garbage|
| (0x100)  |         | (0x500)| (0x504)| (0x508)|
+----------+         +--------+--------+--------+

7. Common Mistakes

  • Memory Leaks: Forgetting to call free().
  • Dangling Pointers: Using a pointer *after* it has been freed. (Always set it to NULL after freeing).
  • Not checking for NULL: If the computer is out of memory, malloc returns NULL. If you try to use it, the program crashes.
  • Buffer Overrun on Heap: Allocating 5 ints, but writing to ptr[10]. This corrupts the heap.

8. Exercises

  1. 1. Write a program using calloc to allocate memory for 5 floats, print them to prove they are 0, then free them.
  1. 2. Write a program that allocates 3 ints, fills them, uses realloc to expand to 5 ints, fills the rest, and prints all 5.

9. MCQ Quiz with Answers

Question 1

Which library is required for dynamic memory allocation?

Question 2

Where is dynamically allocated memory stored?

Question 3

What does malloc return if it fails to allocate memory?

Question 4

What is the difference between malloc and calloc?

Question 5

Why do we cast the return value of malloc (e.g., (int*) malloc(...))?

Question 6

What function resizes an allocated memory block?

Question 7

What happens if you forget to free() memory?

Question 8

What is a pointer called if it points to freed memory?

Question 9

Which function frees memory?

Question 10

sizeof(int) is used in malloc to ensure:

10. Interview Questions

  • Q: Explain the difference between Stack and Heap memory.
  • Q: What is a memory leak, and how does it happen in C?
  • Q: Why does malloc take a sizeof operator instead of just a number?

11. Summary

Dynamic Memory Allocation allows programs to request memory on the Heap during execution using malloc, calloc, and realloc. Because C has no automatic garbage collection, programmers must manually release this memory using free() to avoid memory leaks.

12. Next Chapter Recommendation

In Chapter 15: Structures in C, we will learn how to group different data types (like an int age, float gpa, and char[] name) into a single custom data type.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·