Dynamic Memory in C
Subject: Data Structures and Algorithms · Language: C · Level: intermediate · 6 min read
Use malloc, calloc, realloc, and free to create memory at runtime and handle it safely.
Dynamic memory means creating memory while the program is running. It is used when the required memory size is not known before execution.
A normal array usually has a size fixed in the code. Dynamic memory allows the user, file data, or program logic to decide the size at runtime.
For example, if a program asks how many marks a student wants to enter, the program can allocate exactly that much memory instead of guessing a fixed array size.
Why Dynamic Memory Is Needed
Fixed arrays are simple, but they are not always flexible. If the array is too small, it cannot store all values. If it is too large, memory is wasted.
Dynamic memory helps when data size changes, when building linked lists, stacks, queues, trees, graphs, and when working with large input.
Header File
Dynamic memory functions are available in `stdlib.h`.
```c
#include <stdlib.h>
```
Without this header file, functions like `malloc`, `calloc`, `realloc`, and `free` should not be used.
malloc
`malloc` allocates a block of memory but does not initialize it. The old values inside that memory are garbage values.
```c
int *arr = malloc(n * sizeof(int));
```
This creates space for `n` integers. The return value is stored in an integer pointer because dynamically allocated array memory is accessed through a pointer.
calloc
`calloc` allocates memory and initializes all bytes to zero.
```c
int *arr = calloc(n, sizeof(int));
```
`calloc` is useful when you want the allocated memory to start with zero values.
realloc
`realloc` changes the size of already allocated memory.
It is useful when an array needs to grow or shrink while the program is running.
For example, if you first allocate memory for 5 numbers and later need space for 10 numbers, `realloc` can resize that memory block.
free
`free` releases memory back to the system. If you allocate memory and do not free it, the program may waste memory.
After freeing memory, the pointer should not be used to access old data. Many programmers assign `NULL` after `free` to avoid accidental use.
Dynamic Array Program
This program asks the user for the array size, allocates memory using `malloc`, reads numbers, and prints the sum and average.
```c
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int n;
int sum = 0;
printf("Enter size: ");
scanf("%d", &n);
if (n <= 0) {
printf("Invalid size\n");
return 0;
}
int *arr = malloc(n * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed\n");
return 1;
}
printf("Enter %d numbers: ", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
sum += arr[i];
}
printf("Numbers: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\nSum = %d\n", sum);
printf("Average = %.2f\n", (float) sum / n);
free(arr);
arr = NULL;
return 0;
}
```
malloc vs calloc
- `malloc` takes one argument: total number of bytes
- `calloc` takes two arguments: number of elements and size of each element
- `malloc` gives uninitialized memory
- `calloc` initializes allocated memory with zero
realloc Example
The `realloc` function is used when already allocated memory needs a new size.
```c
int *larger = realloc(arr, newSize * sizeof(int));
if (larger != NULL) {
arr = larger;
}
```
Do not directly overwrite the original pointer without checking the result. If `realloc` fails, it returns `NULL`, and the original memory address may be lost if you overwrite it carelessly.
Important Points
- Always check whether `malloc` returned `NULL`
- Use `sizeof` instead of guessing memory size
- Free dynamically allocated memory when it is no longer needed
- After `free`, do not use the same pointer unless it is assigned a valid address again
Memory Leak and Dangling Pointer
A memory leak happens when allocated memory is never freed. A dangling pointer happens when a pointer still holds the address of memory that has already been freed.
Good C programs avoid both by freeing memory at the right time and not using a pointer after `free`.
Where Dynamic Memory Is Used
Dynamic memory is used heavily in linked lists, trees, graphs, dynamic arrays, file processing, and programs where the input size is not fixed.
In data structures, each new node is usually created using dynamic memory.
Practice Question
Write a C program that takes `n`, dynamically creates an integer array, reads `n` values, and prints their sum.