Dynamic Memory Allocation (DMA) is one of the most powerful features of C programming. It allows programs to allocate and release memory during runtime, making applications more flexible and memory-efficient.
Instead of allocating memory at compile time, dynamic memory allocation enables programs to request memory only when needed. This is especially useful when the amount of data is unknown in advance.
C provides four standard library functions for dynamic memory allocation through the <stdlib.h> header file:
- malloc() – Allocates a block of memory.
- calloc() – Allocates and initializes memory to zero.
- realloc() – Resizes previously allocated memory.
- free() – Releases allocated memory.
Dynamic memory allocation is widely used in linked lists, stacks, queues, trees, graphs, dynamic arrays, databases, operating systems, game development, and many real-world software applications.
In this chapter, you’ll solve practical dynamic memory allocation programs with complete solutions, sample outputs, explanations, and concepts covered. C Dynamic Memory Allocation Practice Questions with Solutions help to understand the concepts.
1. C Program to Allocate Memory Using malloc()
Problem Statement
Write a C program to allocate memory for an integer using malloc() and store a value.
C Solution
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr;
ptr = (int *)malloc(sizeof(int));
if(ptr == NULL)
{
printf("Memory Allocation Failed.");
return 0;
}
printf("Enter a number: ");
scanf("%d", ptr);
printf("Entered Number = %d", *ptr);
free(ptr);
return 0;
}
Sample Output
Enter a number: 50
Entered Number = 50
Explanation
The malloc() function allocates memory for one integer during runtime. The allocated memory is released using free() after use.
Concepts Covered
- Dynamic Memory Allocation
- malloc()
- free()
- Pointer
2. C Program to Allocate Memory for an Array Using malloc()
Problem Statement
Write a C program to dynamically allocate memory for an array using malloc().
C Solution
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *array;
int size, i;
printf("Enter number of elements: ");
scanf("%d", &size);
array = (int *)malloc(size * sizeof(int));
if(array == NULL)
{
printf("Memory Allocation Failed.");
return 0;
}
printf("Enter array elements:\n");
for(i = 0; i < size; i++)
{
scanf("%d", &array[i]);
}
printf("Array Elements:\n");
for(i = 0; i < size; i++)
{
printf("%d ", array[i]);
}
free(array);
return 0;
}
Sample Output
Enter number of elements: 5
Enter array elements:
10
20
30
40
50
Array Elements:
10 20 30 40 50
Explanation
Memory is allocated according to the number of elements entered by the user. This makes the array size flexible during runtime.
Concepts Covered
- malloc()
- Dynamic Arrays
- Runtime Memory Allocation
- free()
3. C Program to Allocate Memory Using calloc()
Problem Statement
Write a C program to allocate memory using calloc() and display the initialized values.
C Solution
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *array;
int i;
array = (int *)calloc(5, sizeof(int));
if(array == NULL)
{
printf("Memory Allocation Failed.");
return 0;
}
printf("Initialized Values:\n");
for(i = 0; i < 5; i++)
{
printf("%d ", array[i]);
}
free(array);
return 0;
}
Sample Output
Initialized Values:
0 0 0 0 0
Explanation
Unlike malloc(), the calloc() function automatically initializes every allocated memory location to zero.
Concepts Covered
- calloc()
- Memory Initialization
- Dynamic Memory Allocation
- free()
4. C Program to Compare malloc() and calloc()
Problem Statement
Write a C program to compare the behavior of malloc() and calloc().
C Solution
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *mallocArray;
int *callocArray;
int i;
mallocArray = (int *)malloc(5 * sizeof(int));
callocArray = (int *)calloc(5, sizeof(int));
printf("Values allocated using malloc():\n");
for(i = 0; i < 5; i++)
{
printf("%d ", mallocArray[i]);
}
printf("\n\nValues allocated using calloc():\n");
for(i = 0; i < 5; i++)
{
printf("%d ", callocArray[i]);
}
free(mallocArray);
free(callocArray);
return 0;
}
Sample Output
Values allocated using malloc():
Garbage Values
Values allocated using calloc():
0 0 0 0 0
Note: The exact output of
malloc()may vary because it contains uninitialized (garbage) values.
Explanation
malloc()allocates memory but does not initialize it.calloc()allocates memory and initializes all elements to 0.
Concepts Covered
- malloc()
- calloc()
- Memory Initialization
- Dynamic Memory Allocation
5. C Program to Resize Memory Using realloc()
Problem Statement
Write a C program to resize dynamically allocated memory using realloc().
C Solution
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *array;
int i;
array = (int *)malloc(3 * sizeof(int));
printf("Enter 3 numbers:\n");
for(i = 0; i < 3; i++)
{
scanf("%d", &array[i]);
}
array = (int *)realloc(array, 5 * sizeof(int));
printf("Enter 2 more numbers:\n");
for(i = 3; i < 5; i++)
{
scanf("%d", &array[i]);
}
printf("\nAll Numbers:\n");
for(i = 0; i < 5; i++)
{
printf("%d ", array[i]);
}
free(array);
return 0;
}
Sample Output
Enter 3 numbers:
10
20
30
Enter 2 more numbers:
40
50
All Numbers:
10 20 30 40 50
Explanation
The realloc() function changes the size of previously allocated memory while preserving the existing data whenever possible.
Concepts Covered
- realloc()
- Memory Resizing
- Dynamic Arrays
- Runtime Memory Allocation
6. C Program to Store Student Records Using Dynamic Memory Allocation
Problem Statement
Write a C program to dynamically allocate memory for multiple student records and display them.
C Solution
#include <stdio.h>
#include <stdlib.h>
struct Student
{
int rollNumber;
char name[50];
float marks;
};
int main()
{
struct Student *student;
int numberOfStudents, i;
printf("Enter number of students: ");
scanf("%d", &numberOfStudents);
student = (struct Student *)malloc(numberOfStudents * sizeof(struct Student));
if(student == NULL)
{
printf("Memory Allocation Failed.");
return 0;
}
for(i = 0; i < numberOfStudents; i++)
{
printf("\nStudent %d\n", i + 1);
printf("Roll Number: ");
scanf("%d", &student[i].rollNumber);
printf("Name: ");
scanf("%s", student[i].name);
printf("Marks: ");
scanf("%f", &student[i].marks);
}
printf("\nStudent Records\n");
for(i = 0; i < numberOfStudents; i++)
{
printf("\nRoll Number : %d\n", student[i].rollNumber);
printf("Name : %s\n", student[i].name);
printf("Marks : %.2f\n", student[i].marks);
}
free(student);
return 0;
}
Sample Output
Enter number of students: 2
Student 1
Roll Number: 101
Name: Rahul
Marks: 88
Student 2
Roll Number: 102
Name: Aman
Marks: 92
Student Records
Roll Number : 101
Name : Rahul
Marks : 88.00
Roll Number : 102
Name : Aman
Marks : 92.00
Explanation
Memory is dynamically allocated for the required number of student records at runtime using malloc().
Concepts Covered
- Dynamic Memory Allocation
- Structures
- malloc()
- Arrays of Structures
7. C Program to Calculate the Sum of Dynamically Allocated Array Elements
Problem Statement
Write a C program to calculate the sum of array elements using dynamically allocated memory.
C Solution
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *array;
int size, i, sum = 0;
printf("Enter array size: ");
scanf("%d", &size);
array = (int *)malloc(size * sizeof(int));
if(array == NULL)
{
printf("Memory Allocation Failed.");
return 0;
}
printf("Enter elements:\n");
for(i = 0; i < size; i++)
{
scanf("%d", &array[i]);
sum += array[i];
}
printf("Sum = %d", sum);
free(array);
return 0;
}
Sample Output
Enter array size: 5
Enter elements:
10
20
30
40
50
Sum = 150
Explanation
The array size is determined at runtime, making the program flexible and memory-efficient.
Concepts Covered
- Dynamic Arrays
- malloc()
- Loops
- Array Traversal
8. C Program to Find the Largest Element Using Dynamic Memory Allocation
Problem Statement
Write a C program to find the largest element of a dynamically allocated array.
C Solution
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *array;
int size, i, largest;
printf("Enter array size: ");
scanf("%d", &size);
array = (int *)malloc(size * sizeof(int));
if(array == NULL)
{
printf("Memory Allocation Failed.");
return 0;
}
printf("Enter elements:\n");
for(i = 0; i < size; i++)
{
scanf("%d", &array[i]);
}
largest = array[0];
for(i = 1; i < size; i++)
{
if(array[i] > largest)
{
largest = array[i];
}
}
printf("Largest Element = %d", largest);
free(array);
return 0;
}
Sample Output
Enter array size: 5
Enter elements:
22
54
17
98
63
Largest Element = 98
Explanation
The program scans the dynamically allocated array and updates the largest value whenever a bigger element is found.
Concepts Covered
- malloc()
- Dynamic Arrays
- Searching
- Loops
9. C Program to Dynamically Allocate Memory for a String
Problem Statement
Write a C program to dynamically allocate memory for a string using malloc().
C Solution
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *string;
string = (char *)malloc(100 * sizeof(char));
if(string == NULL)
{
printf("Memory Allocation Failed.");
return 0;
}
printf("Enter a string: ");
scanf("%s", string);
printf("Entered String = %s", string);
free(string);
return 0;
}
Sample Output
Enter a string: Programming
Entered String = Programming
Explanation
Instead of using a fixed character array, memory is allocated dynamically to store the string.
Concepts Covered
- Dynamic Memory Allocation
- Character Pointer
- malloc()
- Strings
10. C Program to Copy One Dynamically Allocated String to Another
Problem Statement
Write a C program to copy one dynamically allocated string into another.
C Solution
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char *source;
char *destination;
source = (char *)malloc(100 * sizeof(char));
destination = (char *)malloc(100 * sizeof(char));
if(source == NULL || destination == NULL)
{
printf("Memory Allocation Failed.");
return 0;
}
printf("Enter a string: ");
scanf("%s", source);
strcpy(destination, source);
printf("Copied String = %s", destination);
free(source);
free(destination);
return 0;
}
Sample Output
Enter a string: Computer
Copied String = Computer
Explanation
Memory is dynamically allocated for both strings. The strcpy() function copies the contents from the source string to the destination string.
Concepts Covered
- Dynamic Strings
- malloc()
- strcpy()
- Memory Management
11. C Program to Free Dynamically Allocated Memory
Problem Statement
Write a C program to allocate memory dynamically, use it, and release it using free().
C Solution
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr;
ptr = (int *)malloc(sizeof(int));
if(ptr == NULL)
{
printf("Memory Allocation Failed.");
return 0;
}
*ptr = 250;
printf("Stored Value = %d\n", *ptr);
free(ptr);
ptr = NULL;
printf("Memory Successfully Released.");
return 0;
}
Sample Output
Stored Value = 250
Memory Successfully Released.
Explanation
After using dynamically allocated memory, the free() function releases it back to the operating system. Assigning NULL to the pointer prevents accidental access to freed memory.
Concepts Covered
- free()
- Dynamic Memory
- Dangling Pointer Prevention
- Memory Management
12. C Program to Demonstrate Memory Leak
Problem Statement
Write a C program to demonstrate how a memory leak occurs and how to avoid it.
C Solution
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr;
ptr = (int *)malloc(sizeof(int));
if(ptr == NULL)
{
printf("Memory Allocation Failed.");
return 0;
}
*ptr = 100;
printf("Value = %d\n", *ptr);
/* Always free allocated memory */
free(ptr);
ptr = NULL;
printf("Memory Leak Prevented.");
return 0;
}
Sample Output
Value = 100
Memory Leak Prevented.
Explanation
A memory leak occurs when dynamically allocated memory is never released using free(). Over time, repeated memory leaks can reduce available memory and slow down or crash applications.
Concepts Covered
- Memory Leak
- free()
- Runtime Memory
- Best Practices
13. C Program to Dynamically Allocate a Two-Dimensional Array
Problem Statement
Write a C program to dynamically allocate memory for a 2D array.
C Solution
#include <stdio.h>
#include <stdlib.h>
int main()
{
int rows = 2;
int columns = 3;
int **matrix;
int i, j;
matrix = (int **)malloc(rows * sizeof(int *));
for(i = 0; i < rows; i++)
{
matrix[i] = (int *)malloc(columns * sizeof(int));
}
printf("Enter Matrix Elements:\n");
for(i = 0; i < rows; i++)
{
for(j = 0; j < columns; j++)
{
scanf("%d", &matrix[i][j]);
}
}
printf("\nMatrix:\n");
for(i = 0; i < rows; i++)
{
for(j = 0; j < columns; j++)
{
printf("%d ", matrix[i][j]);
}
printf("\n");
}
for(i = 0; i < rows; i++)
{
free(matrix[i]);
}
free(matrix);
return 0;
}
Sample Output
Enter Matrix Elements:
1 2 3
4 5 6
Matrix:
1 2 3
4 5 6
Explanation
Memory is allocated row by row using pointers, making the matrix size flexible during runtime.
Concepts Covered
- Dynamic 2D Arrays
- Double Pointer
- malloc()
- free()
14. C Program to Resize an Array Using realloc()
Problem Statement
Write a C program to resize a dynamically allocated array using realloc().
C Solution
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *array;
int i;
array = (int *)malloc(3 * sizeof(int));
printf("Enter 3 numbers:\n");
for(i = 0; i < 3; i++)
{
scanf("%d", &array[i]);
}
array = (int *)realloc(array, 6 * sizeof(int));
printf("Enter 3 more numbers:\n");
for(i = 3; i < 6; i++)
{
scanf("%d", &array[i]);
}
printf("\nComplete Array:\n");
for(i = 0; i < 6; i++)
{
printf("%d ", array[i]);
}
free(array);
return 0;
}
Sample Output
Enter 3 numbers:
5
10
15
Enter 3 more numbers:
20
25
30
Complete Array:
5 10 15 20 25 30
Explanation
realloc() increases the memory block size while preserving the existing array elements whenever possible.
Concepts Covered
- realloc()
- Dynamic Arrays
- Memory Resizing
- Runtime Allocation
15. C Program to Demonstrate Complete Dynamic Memory Allocation Workflow
Problem Statement
Write a C program demonstrating the complete workflow of dynamic memory allocation using malloc() and free().
C Solution
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr;
int i;
ptr = (int *)malloc(5 * sizeof(int));
if(ptr == NULL)
{
printf("Memory Allocation Failed.");
return 0;
}
printf("Enter 5 numbers:\n");
for(i = 0; i < 5; i++)
{
scanf("%d", &ptr[i]);
}
printf("\nStored Numbers:\n");
for(i = 0; i < 5; i++)
{
printf("%d ", ptr[i]);
}
free(ptr);
ptr = NULL;
printf("\n\nMemory Successfully Released.");
return 0;
}
Sample Output
Enter 5 numbers:
10
20
30
40
50
Stored Numbers:
10 20 30 40 50
Memory Successfully Released.
Explanation
This program demonstrates the complete lifecycle of dynamically allocated memory:
- Allocate memory using
malloc() - Store data
- Access data
- Release memory using
free() - Set the pointer to
NULL
Concepts Covered
- malloc()
- free()
- Dynamic Arrays
- Memory Management
- Runtime Allocation
Chapter Summary
In this chapter, you learned how Dynamic Memory Allocation (DMA) allows C programs to allocate memory during runtime. You practiced using malloc(), calloc(), realloc(), and free() to create dynamic arrays, strings, structures, and two-dimensional arrays. You also learned how to prevent memory leaks, safely release allocated memory, and optimize memory usage. Dynamic memory allocation is a fundamental concept for developing efficient and scalable C applications.
Key Takeaways
- Dynamic memory is allocated during program execution.
malloc()allocates uninitialized memory.calloc()allocates memory initialized to zero.realloc()changes the size of previously allocated memory.free()releases dynamically allocated memory.- Always check whether memory allocation succeeds before using it.
- Always free allocated memory to avoid memory leaks.
- Assign
NULLto pointers after callingfree(). - Dynamic memory allocation is widely used in linked lists, trees, graphs, and dynamic data structures.
- Proper memory management improves program efficiency and reliability.
Frequently Asked Questions (FAQs)
1. What is Dynamic Memory Allocation in C?
Dynamic Memory Allocation is the process of allocating memory during runtime instead of compile time.
2. What is the difference between malloc() and calloc()?
malloc()allocates memory without initializing it.calloc()allocates memory and initializes all bytes to zero.
3. What is realloc() used for?
realloc() resizes an existing dynamically allocated memory block while attempting to preserve its contents.
4. Why is free() important?
free() releases unused memory back to the operating system and helps prevent memory leaks.
5. What is a memory leak?
A memory leak occurs when dynamically allocated memory is never released using free(), causing unnecessary memory consumption.
6. Why should a pointer be set to NULL after calling free()?
Setting a pointer to NULL prevents it from becoming a dangling pointer, reducing the risk of accidentally accessing freed memory.
7. Where is Dynamic Memory Allocation used?
Dynamic memory allocation is commonly used in linked lists, stacks, queues, trees, graphs, dynamic arrays, operating systems, databases, game development, and networking applications.
8. Why is Dynamic Memory Allocation important for interviews?
Dynamic Memory Allocation is a core C programming topic and is frequently asked in technical interviews because it demonstrates understanding of memory management, pointers, runtime allocation, and efficient resource handling.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
