Mastering `new` and `delete` in C++: Dynamic Memory Management
In C++, managing memory dynamically is crucial for efficient and robust program design. This module delves into the fundamental operators
new
delete
The `new` Operator: Allocating Memory
The
new
new
new
std::bad_alloc
`new` allocates memory on the heap and returns a pointer.
The new
operator allocates memory for a single object or an array of objects. It handles the process of finding available memory and returning its address. For objects, it also calls the appropriate constructor.
When you write Type* ptr = new Type;
, the C++ runtime environment searches for a contiguous block of memory large enough to hold an object of Type
. If successful, it constructs the object in that memory location and assigns the address of the allocated memory to the pointer ptr
. For arrays, Type* arr = new Type[size];
allocates memory for size
objects of Type
and returns a pointer to the first element.
The `delete` Operator: Deallocating Memory
The
delete
new
new
`delete` frees memory allocated by `new`.
The delete
operator deallocates memory previously allocated by new
. For objects, it first calls the object's destructor before releasing the memory. It's essential to use delete
exactly once for each new
allocation.
When you use delete ptr;
, the destructor for the object pointed to by ptr
is called first. After the destructor completes, the memory block pointed to by ptr
is returned to the heap. For arrays allocated with new[]
, you must use delete[] ptr;
to ensure that the destructor is called for each element in the array and the entire array's memory is deallocated correctly. Using delete
on a pointer that was not allocated with new
, or deleting the same memory twice, results in undefined behavior.
Feature | new | delete |
---|---|---|
Purpose | Allocate memory on the heap | Deallocate memory on the heap |
Return Value | Pointer to allocated memory | None (void) |
Exception on Failure | std::bad_alloc (by default) | None (but dereferencing invalid pointer is UB) |
Associated Operation | Constructor call (for objects) | Destructor call (for objects) |
Array Usage | new Type[size] | delete[] ptr |
Common Pitfalls and Best Practices
Several common mistakes can lead to memory-related bugs. These include memory leaks (forgetting to
delete
delete
Always pair new
with delete
and new[]
with delete[]
. After deleting a pointer, set it to nullptr
to prevent accidental reuse.
Modern C++ strongly encourages the use of smart pointers (like
std::unique_ptr
std::shared_ptr
new
delete
Illustrative Example: Dynamic Array
Consider allocating a dynamic array of integers. First, we use new int[size]
to get memory for size
integers. We store the pointer. When we are done with the array, we must use delete[]
with the same pointer to free the memory. This ensures that all elements are properly deallocated and the memory is returned to the system.
Text-based content
Library pages focus on text content
The
new
delete
Learning Resources
A comprehensive explanation of the `new` and `delete` operators in C++, including syntax, usage, and common examples.
Official documentation for the `new` operator, detailing its behavior, exceptions, and placement syntax.
An excellent overview of smart pointers in modern C++, explaining how they automate memory management and reduce reliance on manual `new` and `delete`.
A step-by-step tutorial covering dynamic memory allocation in C++, with clear examples of `new` and `delete`.
A detailed tutorial from LearnCpp.com that thoroughly explains the nuances of `new`, `delete`, `new[]`, and `delete[]`.
Reference documentation for the `new` operator, including its overloadable versions and related functions.
Discusses common causes of memory leaks and strategies for detecting and preventing them, often related to improper `new`/`delete` usage.
A video tutorial that visually explains dynamic memory allocation in C++ using `new` and `delete`.
An explanation of the `delete` operator in C++, focusing on its role in deallocating memory and preventing memory leaks.
An excerpt from Scott Meyers' influential book, advocating for RAII (Resource Acquisition Is Initialization) and smart pointers over manual `new`/`delete`.