Dynamic memory allocation in C++ refers to the process of allocating memory during the program’s execution (runtime), rather than at compile time. This memory is allocated using the new and new[] operators for single variables or arrays, and deallocated using the delete and delete[] operators.
1. new Operator (Single Variable)
The new operator is used to allocate memory for a single object or variable of a specific type. It returns a pointer to the allocated memory.
Syntax:
type* pointer = new type;
Example:
int* ptr = new int; // Allocates memory for a single integer
*ptr = 20; // Assign a value to the allocated memory
2. new[] Operator (Array of Variables)
The new[] operator is used to allocate memory for an array of objects.
Syntax:
type* pointer = new type[size];
Example:
int* arr = new int[5]; // Allocates memory for an array of 5 integers
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
3. delete Operator (Single Variable)
The delete operator is used to deallocate memory allocated using the new operator. It frees the memory to be reused.
Syntax:
delete pointer;
Example:
delete ptr; // Deallocates memory allocated for a single integer
4. delete[] Operator (Array of Variables)
The delete[] operator is used to deallocate memory allocated for an array of objects using the new[] operator.
Syntax:
delete[] pointer;
Example:
delete[] arr; // Deallocates memory allocated for an array of integers
Complete Example:
#include
using namespace std;
int main() {
// Dynamic memory allocation for a single variable
int* num = new int;
*num = 5;
cout << "Value of num: " << *num << endl;
// Dynamic memory allocation for an array
int* arr = new int[5];
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
cout << "Array values: ";
for (int i = 0; i < 5; ++i) {
cout << arr[i] << " ";
}
cout << endl;
// Deallocate memory
delete num;
delete[] arr;
return 0;
}
Output:
Array values: 10 20 30 40 50
C++ Dynamic memory allocation – Interview Questions
Q 1: What is dynamic memory allocation?
Ans: Allocating memory at runtime.
Q 2: Operator used for allocation?
Ans: new.
Q 3: Operator used for deallocation?
Ans: delete.
Q 4: Advantage of dynamic allocation?
Ans: Efficient memory usage.
Q 5: What causes memory leak?
Ans: Not freeing allocated memory.
C++ Dynamic memory allocation – Objective Questions (MCQs)
Q1. Which operator is used for dynamic memory allocation in C++?
Q2. Which operator is used to deallocate memory allocated by new?
Q3. What is the correct way to allocate memory for an array of 10 integers dynamically?
Q4. What happens if you forget to free dynamically allocated memory?
Q5. Which keyword can be used with new to handle allocation failure safely?