Dynamic Memory Allocation
📘 C
👁 30 views
📅 Dec 22, 2025
⏱ Estimated reading time: 2 min
Dynamic Memory Allocation (DMA) allows a program to allocate and deallocate memory at runtime using functions provided in stdlib.h.
Need for Dynamic Memory Allocation
-
Memory size can be decided at runtime
-
Efficient use of memory
-
Useful when size of data is unknown in advance
Memory Allocation Functions
| Function | Purpose |
|---|---|
malloc() | Allocates single block of memory |
calloc() | Allocates multiple blocks and initializes to zero |
realloc() | Resizes previously allocated memory |
free() | Releases allocated memory |
1. malloc() Function
Allocates memory without initialization.
Syntax
Example
2. calloc() Function
Allocates memory and initializes all bytes to zero.
Syntax
Example
3. realloc() Function
Changes the size of previously allocated memory.
Syntax
4. free() Function
Releases allocated memory.
Syntax
Example Program
Differences: malloc() vs calloc()
| Feature | malloc | calloc |
|---|---|---|
| Initialization | No | Yes (zero) |
| Arguments | One | Two |
| Speed | Faster | Slower |
Advantages of DMA
-
Efficient memory usage
-
Flexible memory allocation
-
Prevents memory wastage
Precautions
-
Always check for
NULLpointer -
Free memory after use
-
Avoid memory leaks
Summary
-
DMA allocates memory at runtime
-
stdlib.hprovides DMA functions -
malloc,calloc,realloc, andfreeare used -
Proper memory management is essential
🔒 Some advanced sections are available for Registered Members
Register Now
Register Now
Share this Post
← Back to Tutorials