Dynamic Memory Allocation
# CHAPTER 14
Dynamic Memory Allocation
1. Introduction
When you declare an array likeint 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()andcalloc()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).
#### 2. calloc() - Contiguous Allocation
Similar to malloc, but it takes two arguments (number of elements, size of element) and initializes all bits to zero.
#### 3. realloc() - Re-allocation
Resizes a previously allocated memory block. Useful if your array gets full and you need more space.
#### 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().
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.6. Visualizing the Heap
7. Common Mistakes
-
Memory Leaks: Forgetting to call
free().
-
Dangling Pointers: Using a pointer *after* it has been freed. (Always set it to
NULLafter freeing).
-
Not checking for NULL: If the computer is out of memory,
mallocreturnsNULL. 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.
Write a program using
callocto allocate memory for 5 floats, print them to prove they are 0, then free them.
-
2.
Write a program that allocates 3 ints, fills them, uses
reallocto expand to 5 ints, fills the rest, and prints all 5.
9. MCQ Quiz with Answers
Which library is required for dynamic memory allocation?
Where is dynamically allocated memory stored?
What does malloc return if it fails to allocate memory?
What is the difference between malloc and calloc?
Why do we cast the return value of malloc (e.g., (int*) malloc(...))?
What function resizes an allocated memory block?
What happens if you forget to free() memory?
What is a pointer called if it points to freed memory?
Which function frees memory?
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
malloctake asizeofoperator instead of just a number?
11. Summary
Dynamic Memory Allocation allows programs to request memory on the Heap during execution usingmalloc, 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 anint age, float gpa, and char[] name) into a single custom data type.