๐พ 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 :