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.

Dynamic Memory Allocation in C – Interview Questions

Q 1: What is dynamic memory allocation?
Ans: Allocating memory at runtime.
Q 2: Which functions are used for dynamic memory allocation?
Ans: malloc(), calloc(), realloc(), free().
Q 3: Which header file is required?
Ans: .
Q 4: Where is dynamically allocated memory stored?
Ans: In heap memory.
Q 5: Why is dynamic memory needed?
Ans: When memory size is not known at compile time.

Dynamic Memory Allocation in C – Objective Questions (MCQs)

Q1. What is Dynamic Memory Allocation in C?






Q2. Which header file is needed for dynamic memory functions in C?






Q3. Which of the following is NOT a dynamic memory allocation function in C?






Q4. Which function is used to release dynamically allocated memory?






Q5. What is the return type of malloc() and calloc() functions?






Related Dynamic Memory Allocation in C Topics