C Dynamic Memory โ malloc, calloc, realloc, free Explained
Introduction โ What Is Dynamic Memory in C?
In C programming, dynamic memory refers to memory that is allocated at runtime using functions from the <stdlib.h> library. Unlike static memory (allocated at compile-time), dynamic memory provides flexibility, allowing programs to scale memory usage based on user input or data size.
In this guide, youโll learn:
- The purpose of dynamic memory
- Syntax and usage of
malloc(),calloc(),realloc(), andfree() - Common pitfalls and best practices
- Real-world use cases
Why Use Dynamic Memory?
- Memory needs are unknown at compile time
- Arrays or data structures grow/shrink at runtime
- Avoid wasting memory with large fixed-size allocations
Dynamic memory is allocated on the heap, not the stack.
Key Dynamic Memory Functions
All dynamic memory functions return a void* pointer and require explicit casting if used with specific types.
malloc(size_t size)
Allocates memory of the specified size in bytes. The allocated memory contains garbage values.
int *arr = (int *)malloc(5 * sizeof(int));
- Returns: pointer to allocated memory
- If allocation fails: returns
NULL
calloc(size_t n, size_t size)
Allocates memory for an array of n elements and initializes all to zero.
int *arr = (int *)calloc(5, sizeof(int));
- Safer for numeric data and zero-initialized memory
realloc(void *ptr, size_t new_size)
Resizes the memory block pointed to by ptr to new_size bytes.
arr = (int *)realloc(arr, 10 * sizeof(int));
- May move memory to a new location
- Old content is preserved up to the smaller of the old/new size
free(void *ptr)
Releases previously allocated memory back to the system.
free(arr);
Always use free() to prevent memory leaks.
Example โ Using All Dynamic Memory Functions
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr = (int *)malloc(5 * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed\n");
return 1;
}
for (int i = 0; i < 5; i++) {
arr[i] = i * 10;
}
arr = (int *)realloc(arr, 10 * sizeof(int));
for (int i = 5; i < 10; i++) {
arr[i] = i * 10;
}
for (int i = 0; i < 10; i++) {
printf("%d ", arr[i]);
}
free(arr);
return 0;
}
Common Pitfalls
| Issue | Cause |
|---|---|
| Memory leak | Forgetting to call free() |
| Dangling pointer | Using a pointer after calling free() |
| Double free | Calling free() on the same pointer twice |
| Allocation failure | Not checking if malloc() or calloc() returns NULL |
Use Cases of Dynamic Memory
| Scenario | Function |
|---|---|
| User-defined array size | malloc, calloc |
| Growing a list or buffer | realloc |
| Custom linked list or tree node | malloc, free |
| Data structures (queues, stacks) | All four |
Best Practices
Always check if a pointer returned by malloc, calloc, or realloc is NULL.
Use calloc() instead of malloc() if you need zero-initialized memory.
After calling free(), set the pointer to NULL to avoid accidental use.
Avoid using realloc() on the original pointer directly unless you’re sure it won’t fail:
int *tmp = realloc(arr, new_size);
if (tmp != NULL) {
arr = tmp;
}
Summary โ Recap & Next Steps
Dynamic memory gives C programs the ability to allocate memory on-demand, making them efficient, scalable, and adaptable to changing inputs or data sizes.
Key Takeaways:
- Use
malloc()to allocate memory (uninitialized) - Use
calloc()for zero-initialized memory - Use
realloc()to resize previously allocated memory - Use
free()to release memory and prevent leaks
Real-World Relevance:
Vital in data structures, embedded systems, memory-constrained apps, game engines, and interactive tools.
Frequently Asked Questions (FAQ)
What happens if malloc() fails?
It returns NULL. Always check the return value before using the pointer.
What is the difference between malloc() and calloc()?
malloc() allocates uninitialized memory.calloc() allocates and initializes all bytes to zero.
Can I resize memory allocated with calloc() using realloc()?
Yes. realloc() works on memory allocated using malloc() or calloc().
What happens if I call free() on a NULL pointer?
Nothing. free(NULL) is safe and has no effect.
Is memory automatically freed at program end?
Technically yes, but relying on this is bad practice. Always call free().
Share Now :
