new and delete Operators
Dynamic Memory Allocation using new and delete in C++
C++ new and delete Operators Program
This program helps you to learn the fundamental structure and syntax of C++ programming.
#include <iostream>
using namespace std;
int main() {
// Allocate single integer
int* ptr = new int(10);
cout << "Dynamically allocated integer: " << *ptr << endl;
// Allocate array
int* arr = new int[5];
cout << "\nEnter 5 integers: ";
for (int i = 0; i < 5; i++) {
cin >> arr[i];
}
cout << "Array elements: ";
for (int i = 0; i < 5; i++) {
cout << arr[i] << " ";
}
cout << endl;
// Allocate and initialize array
int* arr2 = new int[5]{1, 2, 3, 4, 5};
cout << "\nInitialized array: ";
for (int i = 0; i < 5; i++) {
cout << arr2[i] << " ";
}
cout << endl;
// Free memory
delete ptr; // Delete single variable
delete[] arr; // Delete array (use delete[])
delete[] arr2; // Delete array
cout << "\nMemory freed successfully" << endl;
// Set pointers to null after deletion
ptr = nullptr;
arr = nullptr;
arr2 = nullptr;
return 0;
}Dynamically allocated integer: 10 Enter 5 integers: 10 20 30 40 50 Array elements: 10 20 30 40 50 Initialized array: 1 2 3 4 5 Memory freed successfully
Understanding new and delete Operators
The new operator allocates memory dynamically at runtime and returns a pointer. The delete operator frees the allocated memory. For arrays, use delete[] instead of delete. Always match new with delete and new[] with delete[]. Failing to delete causes memory leaks. Setting pointers to nullptr after deletion prevents dangling pointer issues.
Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.