Dynamic Memory Allocation in C

C Programming @ Freshers.in

Dynamic memory allocation is a crucial aspect of C programming, allowing you to allocate and deallocate memory as needed during program execution. In this article, we will delve into dynamic memory allocation in C, providing comprehensive examples and insights on how to harness this powerful feature effectively.

Understanding Dynamic Memory Allocation

What is Dynamic Memory Allocation?

Dynamic memory allocation in C refers to the process of requesting memory from the system’s heap at runtime and managing it during program execution. Unlike static memory allocation, where memory is allocated at compile-time, dynamic memory allocation provides flexibility and adaptability to your programs.

The malloc, calloc, and realloc Functions

C provides several functions for dynamic memory allocation:

  • malloc: Allocates a specified amount of memory and returns a pointer to the first byte of the block.
  • calloc: Allocates memory for an array of elements, initializes them to zero, and returns a pointer to the first byte of the block.
  • realloc: Adjusts the size of a previously allocated block of memory.

Example: Using malloc to Allocate Memory

#include <stdio.h>
#include <stdlib.h>
int main() {
    int *numbers;
    int n = 5;
    // Allocate memory for an array of integers
    numbers = (int *)malloc(n * sizeof(int));
    if (numbers == NULL) {
        printf("Memory allocation failed.\n");
        return 1;
    }
    // Initialize the array
    for (int i = 0; i < n; i++) {
        numbers[i] = i * 2;
    }
    // Print the array elements
    for (int i = 0; i < n; i++) {
        printf("numbers[%d] = %d\n", i, numbers[i]);
    }
    // Deallocate the memory
    free(numbers);
    return 0;
}

Output:

numbers[0] = 0
numbers[1] = 2
numbers[2] = 4
numbers[3] = 6
numbers[4] = 8

Dynamic memory allocation is essential for various programming tasks, including:

  • Managing variable-sized data structures.
  • Reading and processing data from files or user input.
  • Creating dynamic data structures like linked lists and trees.
Author: user