Memory Management using new and delete in cpp
Memory Management using new delete in cpp
new
and delete
in C++Introduction
In C++, memory management is an essential concept that allows developers to allocate and deallocate memory dynamically during runtime. This gives programs more flexibility and efficiency, especially when the size of data is not known at compile time.
The operators new
and delete
are used to manage dynamic memory in C++. This tutorial will explain how they work with clear examples.
The amount of memory needed is unknown at compile time.
To create objects or arrays whose lifetime extends beyond the scope of a function.
To manage large data structures efficiently.
new
OperatorThe new
operator is used to allocate memory dynamically from the heap.
dataType *pointer = new dataType; // For single variable
dataType *arrayPointer = new dataType[size]; // For array
#include <iostream>
using namespace std;
int main() {
int *age = new int; // Allocate memory for an integer
*age = 25;
cout << "Age: " << *age << endl;
delete age; // Free allocated memory
return 0;
}
Output:
Age: 25
delete
OperatorThe delete
operator is used to deallocate memory that was allocated using new
. This prevents memory leaks.
delete pointer; // For single variable
delete[] arrayPointer; // For arrays
#include <iostream>
using namespace std;
int main() {
int size = 5;
int *arr = new int[size]; // Allocate memory for 5 integers
for (int i = 0; i < size; i++) {
arr[i] = i + 1;
}
cout << "Array elements: ";
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
delete[] arr; // Free the allocated memory
return 0;
}
Output:
Array elements: 1 2 3 4 5
Always use delete
for every new
to avoid memory leaks.
Use delete[]
for arrays allocated with new[]
.
Accessing deleted memory results in undefined behavior.
Avoid dangling pointers by setting the pointer to nullptr
after deleting.
Imagine a Company dynamically assigning Developer objects during project allocation.
#include <iostream>
using namespace std;
class Developer {
public:
string name;
Developer(string n) : name(n) {}
void show() { cout << "Developer: " << name << endl; }
};
int main() {
Developer *dev = new Developer("Alice");
dev->show();
delete dev; // Free memory after use
dev = nullptr; // Avoid dangling pointer
return 0;
}
Output:
Developer: Alice
Memory management in C++ using new
and delete
is powerful and gives developers control over how memory is allocated and freed. Proper use of these operators helps prevent memory leaks, dangling pointers, and improves the efficiency of C++ applications.