Chapter 12: Dynamic Memory Allocation

This is one of the most powerful features of C. Until now, we declared arrays and variables with fixed size at compile time (like int arr[100];). But what if we don’t know how many elements we need until the program is running? That’s where dynamic memory allocation comes in – we allocate memory while the program is running.

C gives us four important functions for this:

  • malloc()
  • calloc()
  • realloc()
  • free()

All these functions are declared in <stdlib.h> header.

1. Why Do We Need Dynamic Memory Allocation?

Fixed-size arrays have problems:

  • Size must be known at compile time (you can’t say int arr[user_input]; in old C)
  • If you declare int arr[10000]; but only need 10 elements → wastes memory
  • If you need 1 million elements but declared only 1000 → program crashes (array overflow)

Dynamic memory solves these problems:

  • Allocate exactly the memory you need at runtime
  • Resize memory when needed
  • Free memory when you don’t need it anymore → good for memory efficiency

2. malloc() – Memory Allocation (Most Common)

Syntax:

C
  • size = number of bytes you want
  • Returns a void* pointer to the allocated memory (or NULL if failed)
  • Memory is not initialized (contains garbage values)

Example: Allocate array of 5 integers dynamically

C

Note:

  • sizeof(int) = usually 4 bytes
  • n * sizeof(int) = total bytes needed
  • Always cast the void* to correct type (though in modern C it’s optional)

3. calloc() – Contiguous Allocation

Similar to malloc(), but initializes all bytes to 0

Syntax:

C

Example:

C

Difference from malloc():

  • malloc(5 * sizeof(int)) → garbage values
  • calloc(5, sizeof(int)) → all zeros (very useful for arrays and structures)

4. realloc() – Re-allocate (Resize) Memory

Used to change the size of previously allocated memory.

Syntax:

C
  • ptr = old pointer (from malloc/calloc)
  • new_size = new total bytes
  • Returns new pointer (may be different from old one!)

Example: Increase array size from 5 to 10

C

Output:

text

5. free() – Release Memory

Very important! Always free memory when you don’t need it anymore.

C
  • After free(ptr), don’t use ptr again (it becomes dangling pointer)
  • Set ptr = NULL; after free → good practice

6. Memory Leaks and Best Practices

Memory Leak = Allocating memory but forgetting to free it → Program keeps using more and more memory → slow or crash

Best Practices:

  1. Always check if allocation succeeded
    C
  2. Always free() what you malloc()/calloc()/realloc()
  3. Don’t free() the same pointer twice → crash
  4. Don’t use pointer after free() → undefined behavior
  5. After free(), set pointer to NULL
    C
  6. Use one free() per allocation
  7. Be careful with realloc() – if it fails, old memory is still valid

Example of Memory Leak (Bad Code):

C

Correct Code:

C

Today’s Homework

  1. Write a program that asks the user how many numbers they want to store → allocate array dynamically → take input → print sum and average.
  2. Create a dynamic array that grows automatically (use realloc) when user wants to add more numbers.
  3. Write a program that allocates memory for 5 strings using dynamic allocation (use char *str = malloc(100);).
  4. Intentionally create a memory leak and think how you would fix it.

You may also like...