Allocating Memory Dynamically
Dynamic Memory Allocation
Dynamic memory allocation in C allows for the allocation and deallocation of memory during runtime
In C, dynamic memory allocation is performed using the functions
malloc
,calloc
, andrealloc
from the<stdlib.h>
header.These functions allow you to allocate memory dynamically during program execution.
Here's how each function is used:
malloc
- The
malloc
function is used to allocate a block of memory of a specified size. - It takes the number of bytes to allocate as its argument and returns a pointer to the beginning of the allocated memory block.
- The memory allocated by
malloc
is uninitialized, meaning its contents are undefined.
Example
#include <stdio.h>
#include <stdlib.h>
int main() {
int* dynamicArray = malloc(5 * sizeof(int)); // Allocate memory for an array of 5 integers
if (dynamicArray == NULL) {
printf("Failed to allocate memory.\n");
return 1; // Error handling
}
// Use the dynamically allocated memory
free(dynamicArray); // Deallocate the memory when done
return 0;
}
calloc
- The
calloc
function is used to allocate a block of memory for an array of a specified number of elements, each with a specified size. - It takes two arguments: the number of elements and the size of each element.
calloc
initializes the allocated memory block to zero.
Example
#include <stdio.h>
#include <stdlib.h>
int main() {
int* dynamicArray = calloc(5, sizeof(int)); // Allocate memory for an array of 5 integers
if (dynamicArray == NULL) {
printf("Failed to allocate memory.\n");
return 1; // Error handling
}
// Use the dynamically allocated memory
free(dynamicArray); // Deallocate the memory when done
return 0;
}
realloc
- The
realloc
function is used to resize an already allocated memory block. - It takes two arguments: a pointer to the previously allocated memory block and the new size in bytes.
realloc
may move the memory block to a different location if necessary.- If the reallocation fails,
realloc
returnsNULL
and the original memory block remains unchanged.
Example
#include <stdio.h>
#include <stdlib.h>
int main() {
int* dynamicArray = malloc(5 * sizeof(int)); // Allocate memory for an array of 5 integers
if (dynamicArray == NULL) {
printf("Failed to allocate memory.\n");
return 1; // Error handling
}
// Use the dynamically allocated memory
dynamicArray = realloc(dynamicArray, 10 * sizeof(int)); // Resize the array to 10 integers
if (dynamicArray == NULL) {
printf("Failed to reallocate memory.\n");
return 1; // Error handling
}
// Use the resized memory block
free(dynamicArray); // Deallocate the memory when done
return 0;
}
NULL and FREE
After dynamically allocating memory, it's important to check if the allocation was successful by verifying if the returned pointer is
NULL
.If it is
NULL
, it indicates that the allocation failed due to insufficient memory.Remember to deallocate dynamically allocated memory using the
free
function when it's no longer needed to avoid memory leaks.