Overloading new and delete
Understand how to overload the global new and delete operators in C++ to explicitly manage memory allocation and deallocation. Explore techniques to track memory usage, identify leaks through address comparison, and improve application memory transparency. This lesson helps you gain critical skills to avoid memory issues in C++ programs that run over extended periods.
Quite often, a C++ application allocates memory but does not deallocate it. This is a job for the operator new and operator delete. Thanks to both of them, we can explicitly manage the memory of an application.
From time to time, we have to verify that an application correctly releases its memory. In particular, for programs running for long periods of time, it is a challenge to allocate and deallocate memory from a memory management perspective. Of course, the automatic release of memory during program shutdown is not an option.
The baseline #
As a baseline for our analysis, we use a simple program that frequently allocates and deallocates memory.
The key question is, does there need to be a corresponding delete for each new call?
The question can be simply answered by overloading the global operators, new and delete. For each operator, I count how often it was called.
new operator
C++ offers the new operator in four variations:
void* operator new (std::size_t count );
void* operator new[](std::size_t count );
void* operator new (std::size_t count, const std::nothrow_t& ...