How to Use new and delete in C++: Simple Guide
In C++, use
new to allocate memory dynamically and delete to free that memory when no longer needed. For arrays, use new[] and delete[] to manage memory properly and avoid leaks.Syntax
The new operator allocates memory on the heap and returns a pointer to it. Use delete to free that memory. For single objects, use new Type and delete pointer. For arrays, use new Type[size] and delete[] pointer.
- new Type: allocates one object of Type
- new Type[size]: allocates an array of objects
- delete pointer: frees memory of a single object
- delete[] pointer: frees memory of an array
cpp
int* p = new int; // allocate one int int* arr = new int[5]; // allocate array of 5 ints // later delete p; // free single int delete[] arr; // free array
Example
This example shows how to allocate a single integer and an array of integers using new, assign values, print them, and then free the memory with delete and delete[].
cpp
#include <iostream> int main() { int* single = new int; // allocate one int *single = 42; // assign value int* array = new int[3]; // allocate array of 3 ints for (int i = 0; i < 3; ++i) { array[i] = i * 10; // assign values } std::cout << "Single value: " << *single << "\n"; std::cout << "Array values: "; for (int i = 0; i < 3; ++i) { std::cout << array[i] << " "; } std::cout << "\n"; delete single; // free single int delete[] array; // free array return 0; }
Output
Single value: 42
Array values: 0 10 20
Common Pitfalls
Common mistakes include:
- Using
deleteinstead ofdelete[]for arrays causes undefined behavior. - Forgetting to
deleteallocated memory causes memory leaks. - Deleting the same pointer twice causes crashes.
- Using pointers after deleting them leads to undefined behavior.
Always match new with delete and new[] with delete[].
cpp
#include <iostream> int main() { int* arr = new int[3]; // Wrong: using delete instead of delete[] // delete arr; // BAD! // Correct way: delete[] arr; return 0; }
Quick Reference
| Operation | Syntax | Description |
|---|---|---|
| Allocate single object | Type* p = new Type; | Allocates one object and returns pointer |
| Allocate array | Type* p = new Type[size]; | Allocates array of objects |
| Free single object | delete p; | Frees memory allocated for one object |
| Free array | delete[] p; | Frees memory allocated for array |
Key Takeaways
Use new to allocate memory and delete to free it to avoid memory leaks.
Always pair new with delete and new[] with delete[].
Forgetting to delete allocated memory causes leaks; deleting twice causes crashes.
Use delete[] for arrays to avoid undefined behavior.
After deleting, set pointers to nullptr to avoid using invalid memory.