Dynamic memory allocation allows programs to allocate memory at runtime, enabling flexibility in managing memory. This is achieved through functions like malloc()
, calloc()
, and free()
.
-
malloc(): The
malloc()
function allocates a block of memory of a specified size and returns a pointer to it. The memory is not initialized.
int *ptr = (int *)malloc(5 * sizeof(int)); // Allocates memory for 5 integers
if (ptr == NULL) {
printf(“Memory allocation failed.”);
}
- calloc(): The
calloc()
function allocates memory for an array of elements, initializes them to zero, and returns a pointer to the memory. It takes two arguments: the number of elements and the size of each element.