Dynamic Memory Allocation in C (malloc, calloc): Explained with Programs

Dynamic Memory Allocation in C (malloc, calloc)
In C programming, memory can be allocated in two ways: static and dynamic.
Static memory is allocated at compile time, which means the size must be fixed in advance. But in real-life programs, we often don’t know how much memory is required.
This is where dynamic memory allocation becomes important. It allows memory to be allocated during runtime using functions like malloc() and calloc().
malloc() – Theory
The malloc() function is used to allocate a block of memory of a specified size.
• It allocates memory in bytes
• It returns a pointer to the allocated memory
• The memory is NOT initialized (contains garbage values)
Syntax:
ptr = (datatype) malloc(size_in_bytes);
malloc() Program
#include <stdio.h> #include <stdlib.h> int main() { intptr; int n = 5; ptr = (int) malloc(n sizeof(int)); if(ptr == NULL) { printf("Memory not allocated"); return 0; } for(int i = 0; i < n; i++) { ptr[i] = i + 1; } for(int i = 0; i < n; i++) { printf("%d ", ptr[i]); } free(ptr); return 0; }
calloc() – Theory
The calloc() function is used to allocate memory for multiple elements.
• It takes two arguments: number of elements and size of each element
• It initializes all memory locations to 0
• It returns a pointer to allocated memory
Syntax:
ptr = (datatype) calloc(number_of_elements, size_of_each);
calloc() Program
#include <stdio.h> #include <stdlib.h> int main() { intptr; int n = 5; ptr = (int*) calloc(n, sizeof(int)); if(ptr == NULL) { printf("Memory not allocated"); return 0; } for(int i = 0; i < n; i++) { printf("%d ", ptr[i]); } free(ptr); return 0; }
Difference Between malloc() and calloc()
| Feature | malloc() | calloc() |
|---|---|---|
| Initialization | Garbage values | Zero initialized |
| Arguments | 1 argument | 2 arguments |
| Speed | Faster | Slightly slower |
Important Points for Exams
• malloc() does not initialize memory
• calloc() initializes memory with 0
• Always check for NULL pointer
• Always free allocated memory using free()
Final Tip
Understanding logic is more important than memorizing code. Once you understand how memory works, writing programs becomes easy.

Written by
Palak PatelEducation writer Palak Patel covers the latest education news, board exam updates, results, and career opportunities.
Comments
No comments yet. Be the first!
