Library`new` and `delete`

`new` and `delete`

Learn about `new` and `delete` as part of C++ Modern Systems Programming and Performance

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

code
new
and
code
delete
, which are your primary tools for allocating and deallocating memory on the heap during program execution. Understanding these operators is key to preventing memory leaks and ensuring your programs run smoothly.

The `new` Operator: Allocating Memory

The

code
new
operator is used to request memory from the heap at runtime. When you use
code
new
, the system finds a suitable block of memory, initializes it (if a constructor is involved for objects), and returns a pointer to the beginning of that memory block. If memory allocation fails,
code
new
throws a
code
std::bad_alloc
exception by default.

`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

code
delete
operator is the counterpart to
code
new
. It is used to release memory that was previously allocated with
code
new
, returning it to the system for reuse. Proper deallocation is critical to prevent memory leaks, where allocated memory is no longer accessible but remains occupied, eventually leading to program instability or termination.

`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.

Featurenewdelete
PurposeAllocate memory on the heapDeallocate memory on the heap
Return ValuePointer to allocated memoryNone (void)
Exception on Failurestd::bad_alloc (by default)None (but dereferencing invalid pointer is UB)
Associated OperationConstructor call (for objects)Destructor call (for objects)
Array Usagenew Type[size]delete[] ptr

Common Pitfalls and Best Practices

Several common mistakes can lead to memory-related bugs. These include memory leaks (forgetting to

code
delete
), double deletion (calling
code
delete
on the same pointer twice), and using a pointer after it has been deleted (dangling pointer).

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

code
std::unique_ptr
and
code
std::shared_ptr
) which automate memory management, significantly reducing the risk of these errors. However, understanding the underlying
code
new
and
code
delete
is fundamental to grasping how these smart pointers work and for situations where manual memory management is unavoidable.

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

code
new
and
code
delete
operators are powerful but require careful handling. Mastering their usage is a cornerstone of efficient C++ programming, paving the way for more advanced memory management techniques and robust system design.

Learning Resources

C++ `new` and `delete` Operators - GeeksforGeeks(blog)

A comprehensive explanation of the `new` and `delete` operators in C++, including syntax, usage, and common examples.

Dynamic Memory Allocation in C++ - cppreference.com(documentation)

Official documentation for the `new` operator, detailing its behavior, exceptions, and placement syntax.

C++ Smart Pointers: The Definitive Guide(blog)

An excellent overview of smart pointers in modern C++, explaining how they automate memory management and reduce reliance on manual `new` and `delete`.

Understanding `new` and `delete` in C++ - Tutorialspoint(tutorial)

A step-by-step tutorial covering dynamic memory allocation in C++, with clear examples of `new` and `delete`.

C++ Memory Management: `new`, `delete`, `new[]`, `delete[]`(tutorial)

A detailed tutorial from LearnCpp.com that thoroughly explains the nuances of `new`, `delete`, `new[]`, and `delete[]`.

The C++ `new` operator - Cplusplus.com Reference(documentation)

Reference documentation for the `new` operator, including its overloadable versions and related functions.

Memory Leaks in C++: How to Detect and Prevent Them(blog)

Discusses common causes of memory leaks and strategies for detecting and preventing them, often related to improper `new`/`delete` usage.

C++ Dynamic Memory Allocation Explained(video)

A video tutorial that visually explains dynamic memory allocation in C++ using `new` and `delete`.

C++ `delete` Operator - javatpoint(blog)

An explanation of the `delete` operator in C++, focusing on its role in deallocating memory and preventing memory leaks.

Effective C++: Item 13: Use objects to manage resources(paper)

An excerpt from Scott Meyers' influential book, advocating for RAII (Resource Acquisition Is Initialization) and smart pointers over manual `new`/`delete`.