What is dynamic memory allocation in C? Explain malloc(), calloc(), and free() functions with examples.

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.
int *ptr = (int *)calloc(5, sizeof(int)); // Allocates memory for 5 integers, initialized to zero
if (ptr == NULL) {
printf(“Memory allocation failed.”);
}
  • free(): The free() function is used to release the memory allocated by malloc() or calloc(). This helps prevent memory leaks.
free(ptr); // Releases the memory allocated to ptr
These functions are critical in managing memory in C, especially when working with dynamic data structures like linked lists or arrays where the size is not known in advance.