new and delete Operators in C++
Dynamic Memory Allocation using new and delete in C++.
BeginnerMemory Management ProgramsExample 7 of 11
new-and-delete-operators.cpp
1#include <iostream>2using namespace std;34int main() {5 // Allocate single integer6 int* ptr = new int(10);7 cout << "Dynamically allocated integer: " << *ptr << endl;89 // Allocate array10 int* arr = new int[5];11 cout << "\nEnter 5 integers: ";12 for (int i = 0; i < 5; i++) {13 cin >> arr[i];14 }1516 cout << "Array elements: ";17 for (int i = 0; i < 5; i++) {18 cout << arr[i] << " ";19 }20 cout << endl;2122 // Allocate and initialize array23 int* arr2 = new int[5]{1, 2, 3, 4, 5};24 cout << "\nInitialized array: ";25 for (int i = 0; i < 5; i++) {26 cout << arr2[i] << " ";27 }28 cout << endl;2930 // Free memory31 delete ptr; // Delete single variable32 delete[] arr; // Delete array (use delete[])33 delete[] arr2; // Delete array3435 cout << "\nMemory freed successfully" << endl;3637 // Set pointers to null after deletion38 ptr = nullptr;39 arr = nullptr;40 arr2 = nullptr;4142 return 0;43}
Output
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
What's going on
The program demonstrates dynamic memory allocation:
Allocating single variable using new
Allocating arrays using new[]
Initializing allocated memory
Freeing memory using delete and delete[]
Setting pointers to nullptr after deletion
Dynamic memory allows allocation at runtime when size is unknown at compile time.
Header File Used
This header provides:
cout for displaying output
cin for taking input from the user
1#include <iostream>
Understanding new Operator
new Operator Concept
:
Allocates memory dynamically at runtime
Returns pointer to allocated memory
Memory allocated on heap (not stack)
Size determined at runtime
Syntax
:
pointer = new dataType; // Single variable
pointer = new dataType(value); // With initialization
pointer = new dataType[size]; // Array
Allocating Single Variable
Basic Allocation
:
int* ptr = new int(10);
How it works
:
Allocates memory for one integer
Initializes with value 10
Returns pointer to allocated memory
Memory exists until explicitly deleted
Accessing Value
:
*ptr // Accesses value 10
Allocating Arrays
Array Allocation
:
int* arr = new int[5];
How it works
:
Allocates memory for 5 integers
Returns pointer to first element
Elements can be accessed like array: arr[0], arr[1]
Size can be determined at runtime
Initialized Array
:
int* arr2 = new int[5]{1, 2, 3, 4, 5};
How it works
:
Allocates and initializes array
Values provided in braces
Useful for pre-filled arrays
Understanding delete Operator
delete Operator Concept
:
Frees memory allocated by new
Returns memory to system
Prevents memory leaks
Must match new with delete
Syntax
:
delete pointer; // Single variable
delete[] pointer; // Array
Freeing Single Variable
Deleting Single Variable
:
delete ptr;
How it works
:
Frees memory allocated by new
Does not delete pointer variable
Pointer still exists but points to invalid memory
Should set to nullptr after deletion
Freeing Arrays
Deleting Arrays
:
delete[] arr; // Use delete[] for arrays
Important Rule
:
Use delete[] for arrays allocated with new[]
Using delete instead of delete[] causes undefined behavior
Always match new[] with delete[]
Why delete[]?
Arrays need special cleanup
delete[] calls destructors for all elements
delete only frees first element's memory
Setting Pointers to Null
After Deletion
:
delete ptr;
ptr = nullptr; // Good practice
Why?
Prevents dangling pointer
Can check if pointer was deleted
Prevents accidental reuse
Makes code safer
When to Use new/delete
Best For
:
Size unknown at compile time
Large objects (avoid stack overflow)
Objects with variable lifetime
Dynamic data structures
Polymorphism with base pointers
Example Scenarios
:
User-determined array sizes
Large matrices or data structures
Objects that outlive function scope
Linked lists, trees, graphs
Important Considerations
Memory Leaks
:
Always delete what you new
Forgetting delete causes memory leak
Memory not returned to system
Can cause program to run out of memory
Matching Operators
:
new must match with delete
new[] must match with delete[]
Mismatch causes undefined behavior
Exception Safety
:
If exception occurs, delete may not be called
Use smart pointers (C++11) for automatic cleanup
RAII (Resource Acquisition Is Initialization) pattern
return 0;
This ends the program successfully.