Dynamic Memory Allocation
Dynamic Memory Allocation
int main() {
// 1. malloc: Allocate memory for an array of 5 integers
int *arr = (int *)malloc(5 * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed\n");
return 1;
}
return 0;
}
Explanation
1. malloc:
o Allocates a specified number of bytes in memory but does not
initialize the memory.
o The malloc(5 * sizeof(int)) call allocates memory for 5 integers (20
bytes if sizeof(int) is 4).
o The returned memory may contain garbage values.
2. calloc:
o Allocates memory for an array of elements and initializes all elements
to 0.
o The calloc(5, sizeof(int)) call allocates memory for 5 integers and
initializes them to zero.
3. realloc:
o Resizes a previously allocated memory block to a new size.
Output
Memory allocated using malloc:
12345
Memory allocated using calloc (initialized to 0):
00000
Memory after realloc (expanded to 10 integers):
1 2 3 4 5 6 7 8 9 10
Memory freed successfully.
Key Points
Always check the return value of malloc, calloc, and realloc to ensure
memory allocation was successful.
Use free to release memory when it’s no longer needed.
Avoid using freed memory (this is called a "dangling pointer" issue).