Dynamic Memory Allocation in C
So far, every array had a fixed size written in the code, like int marks[100]. What if a class has 5 students today and 500 tomorrow? A fixed array either wastes memory or runs out of space.
Dynamic memory allocation lets your program ask for exactly as much memory as it needs while it is running, and give it back when done. This lesson explains the idea, the stack and the heap, and the four functions you'll use: malloc, calloc, realloc and free.
What You Will Learn
- What static and dynamic memory allocation mean.
- The difference between stack and heap memory.
- Why dynamic allocation is needed.
- The four memory functions in
stdlib.h. - The basic steps: allocate, check, use, free.
What is Dynamic Memory Allocation in C?
Exam definition: Dynamic memory allocation is the process of allocating memory at run time from the heap using library functions (malloc, calloc, realloc) and releasing it with free. In static allocation, the size is fixed at compile time.
Memory trick: Static allocation is like booking a fixed hall for a wedding months in advance: same size whether 50 or 500 guests come. Dynamic allocation is like adding chairs as guests arrive and returning them after the function. You must return the chairs (free), or the rental shop runs out.
Stack vs Heap Memory
High addresses
+------------------+
| STACK | local variables, function calls
| | | grows down, freed automatically
| v |
| |
| ^ |
| | |
| HEAP | malloc / calloc / realloc
+------------------+ you free it yourself
| global/static |
+------------------+
| program code |
+------------------+
Low addresses
| Point | Stack (static/automatic) | Heap (dynamic) |
|---|---|---|
| When size is decided | Compile time | Run time |
| Who frees it | Automatically, when the function ends | You, with free() |
| Size limit | Small (a few MB) | Large (most of the RAM) |
| Can resize? | No | Yes, with realloc |
| Accessed by | Variable name | A pointer |
| Lifetime | Until the block ends | Until you free it |
Syntax of the Memory Functions
All four are declared in <stdlib.h>.
void *malloc(size_t size); /* size bytes, NOT initialized */
void *calloc(size_t count, size_t size); /* count*size bytes, set to 0 */
void *realloc(void *ptr, size_t new_size); /* resize an existing block */
void free(void *ptr); /* give the block back */
| Function | Job | Returns |
|---|---|---|
malloc | Memory allocation: one block of given bytes | Pointer, or NULL if it fails |
calloc | Contiguous allocation: n items, all zeroed | Pointer, or NULL |
realloc | Re-allocation: grow or shrink a block | New pointer, or NULL |
free | Release a block | Nothing |
They return void * (a generic pointer), which C converts automatically to your pointer type.
The four steps every time
1. ALLOCATE p = malloc(n * sizeof(int));
2. CHECK if (p == NULL) { handle the error }
3. USE p[0] = 5; ...
4. FREE free(p); p = NULL;
Example 1: Array Size Chosen by the User
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int n, i, total = 0;
int *marks;
printf("How many students? ");
scanf("%d", &n);
marks = malloc(n * sizeof(int)); /* 1. allocate exactly n ints */
if (marks == NULL) /* 2. check */
{
printf("Not enough memory\n");
return 1;
}
printf("Enter %d marks: ", n);
for (i = 0; i < n; i++) /* 3. use like an array */
{
scanf("%d", &marks[i]);
total += marks[i];
}
printf("Average = %.2f\n", (float) total / n);
free(marks); /* 4. free */
marks = NULL;
return 0;
}
Output
How many students? 4 Enter 4 marks: 70 85 60 95 Average = 77.50
Code Explanation
- The size
nis known only after the user types it, so a fixed array can't be sized correctly.mallocsolves this. n * sizeof(int)asks for exactly enough bytes for n integers. Usingsizeofkeeps the code correct on any system.- If memory isn't available,
mallocreturnsNULL. We check before using it. - The pointer
marksis used exactly like an array:marks[i]means*(marks + i). free(marks)returns the memory. Settingmarks = NULLprevents a dangling pointer.
How Heap Memory Lives Beyond a Function
Local arrays die when their function returns. Heap memory stays alive until you free it, so a function can create memory and hand it to the caller. This was impossible with local arrays (remember: never return a local address).
Example 2: A Function That Creates and Returns an Array
#include <stdio.h>
#include <stdlib.h>
int *make_table(int number, int count) /* returns heap memory */
{
int *t = malloc(count * sizeof(int));
int i;
if (t == NULL)
return NULL;
for (i = 0; i < count; i++)
t[i] = number * (i + 1);
return t; /* safe: heap memory survives */
}
int main(void)
{
int *table = make_table(7, 5);
int i;
if (table == NULL)
return 1;
printf("Table of 7:");
for (i = 0; i < 5; i++)
printf(" %d", table[i]);
printf("\n");
free(table); /* caller frees it */
table = NULL;
printf("Memory freed\n");
return 0;
}
Output
Table of 7: 7 14 21 28 35 Memory freed
make_tableallocates on the heap and returns the pointer. The memory is still valid inmain.- Rule: whoever ends up owning the pointer must call
freeonce. Here, that'smain.
Advantages and Disadvantages of Dynamic Allocation
| Advantages | Disadvantages |
|---|---|
| Size decided at run time: no waste | You must remember to free (or memory leaks) |
| Can grow or shrink with realloc | Slower than stack allocation |
| Memory can outlive the function | Bugs: dangling pointers, double free |
| Large blocks possible | Accessed only through pointers |
| Needed for linked lists, trees, graphs | Heap can become fragmented |
Important Points to Remember
- Dynamic memory comes from the heap at run time.
- Include <stdlib.h>.
- malloc (bytes), calloc (zeroed), realloc (resize), free (release).
- Always use sizeof to compute sizes.
- Always check for NULL after allocating.
- Every allocation needs exactly one free; then set the pointer to NULL.
Common Mistakes Beginners Make
| Mistake | What happens | Fix |
|---|---|---|
malloc(n) for n ints | Only n bytes: overflow when writing | malloc(n * sizeof(int)) |
| Not checking for NULL | Crash if memory runs out | if (p == NULL) |
Forgetting free | Memory leak | Free when done |
Using memory after free | Dangling pointer: random bugs | Set p = NULL after free |
Forgetting #include <stdlib.h> | Warnings, wrong pointer on some systems | Include it |
Dynamic Memory Allocation Practice Questions
- What is the difference between static and dynamic memory allocation?
- Name the four dynamic memory functions and their header file.
- What does malloc return if it fails?
- Why can a function return heap memory but not a local array?
- Give two disadvantages of dynamic memory allocation.
Show answers
- Static: size fixed at compile time, memory managed automatically (stack/global). Dynamic: size decided at run time, memory from the heap, freed by the programmer.
- malloc, calloc, realloc, free, in
<stdlib.h>. NULL.- Heap memory lives until freed; a local array is destroyed when the function returns.
- Risk of memory leaks if not freed; dangling pointer/double-free bugs; slower than stack (any two).
Coding Exercise
Allocate memory for n floats (n = 3: prices 99.5, 250.0, 45.25), store the prices, print the total, then free the memory.
Show solution
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int n = 3, i;
float values[] = {99.5f, 250.0f, 45.25f};
float *price = malloc(n * sizeof(float));
float total = 0;
if (price == NULL)
return 1;
for (i = 0; i < n; i++)
{
price[i] = values[i];
total += price[i];
}
printf("Total = %.2f\n", total);
free(price);
price = NULL;
return 0;
}
Total = 394.75
Quick Quiz: Dynamic Memory Allocation (MCQ)
-
Dynamic memory is allocated from the:
A) Stack B) Heap C) Register D) Code segment
-
Header file for malloc and free:
A)
stdio.hB)string.hC)stdlib.hD)memory.honly -
malloc returns a pointer of type:
A)
int *B)char *C)void *D)float * -
Memory from malloc is released by:
A) The compiler B)
free()C) The end of the function D)delete -
Static memory allocation happens at:
A) Run time B) Compile time C) Link time only D) Never
Show answers
- B: heap.
- C:
stdlib.h. - C:
void *. - B:
free(). - B: compile time.
Quick Revision for Exams and Interviews
Read this before your exam. The highlighted words are the answer.
Must-remember facts
| Dynamic allocation | Memory at run time from the heap |
|---|---|
| Header | <stdlib.h> |
| Functions | malloc, calloc, realloc, free |
| Return type | void *; NULL on failure |
| Stack memory | Freed automatically |
| Heap memory | Freed by you with free() |
| Steps | Allocate → check → use → free |
Frequently asked questions
- What is dynamic memory allocation?
- Allocating memory at run time from the heap with malloc/calloc/realloc and releasing it with free.
- What is the difference between stack and heap?
- Stack: automatic, small, fixed sizes. Heap: manual (free), large, sizes chosen at run time.
- Why is dynamic memory allocation needed?
- When the amount of data is unknown until run time, or memory must outlive a function, or must grow (linked lists, trees).
Remember
- Dynamic = add chairs as guests arrive, and return them.
- Every malloc needs one free.
Next Topic
Next lesson: malloc() Function in C. You will study malloc() in detail: its syntax, how it works and how to use it with structures.