Dynamic Memory Allocation Functions in C

Dynamic memory allocation functions in C allow you to allocate and deallocate memory dynamically during program execution. They are commonly used when you need memory whose size is determined at runtime, such as when working with arrays or structures of unknown size. C provides several standard library functions for dynamic memory management, including malloc(), calloc(), realloc(), and free().

Here's a brief explanation of these functions:

  1. malloc(size_t size): The malloc() function (memory allocation) is used to allocate a block of memory of the specified size in bytes. It returns a pointer to the first byte of the allocated memory block. If memory allocation fails, it returns NULL.
  2. calloc(size_t num_elements, size_t element_size): The calloc() function (contiguous allocation) is used to allocate a block of memory for an array of elements. It takes two arguments: the number of elements to allocate and the size of each element in bytes. It initializes the allocated memory to zero and returns a pointer to the first byte of the allocated memory block. If memory allocation fails, it returns NULL.
  3. realloc(void *ptr, size_t new_size): The realloc() function (reallocate memory) is used to change the size of a previously allocated memory block. It takes a pointer to the previously allocated memory block (ptr) and the new size in bytes. It returns a pointer to the new memory block. If reallocation fails, it returns NULL. If ptr is NULL, realloc() behaves like malloc().
  4. free(void *ptr): The free() function is used to deallocate memory that was previously allocated using malloc(), calloc(), or realloc(). It does not return a value, and it takes a pointer to the memory block to be deallocated.

Here's a simple example demonstrating the use of these functions:

#include <stdio.h>
#include <stdlib.h>

int main() {
    int *arr;
    int n = 5;

    // Allocate memory for an integer array of size n
    arr = (int *)malloc(n * sizeof(int));

    if (arr == NULL) {
        printf("Memory allocation failed!\n");
        return 1; // Exit with an error code
    }

    // Initialize the array
    for (int i = 0; i < n; i++) {
        arr[i] = i * 10;
    }

    // Print the array
    for (int i = 0; i < n; i++) {
        printf("arr[%d] = %d\n", i, arr[i]);
    }

    // Deallocate the memory
    free(arr);

    return 0;
}

Dynamic memory allocation is a powerful feature in C, but it also comes with the responsibility of deallocating memory to prevent memory leaks. It's essential to check for allocation failures and free memory when it's no longer needed.