Dynamic Memory Allocation in C

Dynamic memory allocation in C refers to the process of allocating memory at runtime, rather than at compile time. This allows you to allocate memory for variables or arrays based on the size required during the execution of the program, giving you more flexibility in managing memory.

There are some functions to allocate dynamic memory.

1. malloc(size_t size): It is used to allocates a block of memory of the specified size.

2. calloc(size_t num, size_t size): It is used to allocates memory for an array of num elements, each of size size bytes.

3. realloc(void* ptr, size_t size): It is used to resizes a previously allocated memory block (pointed to by ptr) to the new size.

4. free(void* ptr): It is used to free the memory block pointed to by ptr that was previously allocated by malloc, calloc, or realloc.

Example:


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

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

    // Allocating memory for 10 integers dynamically
    arr = (int*) malloc(n * sizeof(int));

    if (arr == NULL) {
        printf("Memory allocation failed!\n");
        return 1; // Exit the program if memory allocation fails
    }

    // Assigning values to the allocated memory
    for (int i = 0; i < n; i++) {
        arr[i] = i * 10;
    }

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

    // Freeing the allocated memory
    free(arr);

    return 0;
}

Output:

0 10 20 30 40 50 60 70 80 90

Use of Dynamic Memory Allocation

1. You can allocate memory dynamically based on the user's input or the size of the data you're working with, which makes your program more flexible.

2. It allows efficient use of memory, especially when dealing with large data structures (arrays, lists, etc.), and helps you avoid stack overflow due to large local variables.