I want to write a header file for c++. When included in a program, the header file overloads the new
and delete
operators so that it can count the number of allocations and deallocations. The header file will also print out the number of allocations and deallocations when the program exits. Is this the proper way to go about doing that? Will this code cause any problems or leave any gaps? The header file is only meant to be included when debugging.
#pragma once
#include <cstdint>
#include <cstdlib>
size_t __allocations = 0;
void* operator new(std::size_t sz) {
++__allocations;
return std::malloc(sz);
}
size_t __array_allocations = 0;
void* operator new[](std::size_t sz) {
++__array_allocations;
return std::malloc(sz);
}
size_t __deallocations = 0;
void operator delete(void* ptr) noexcept
{
++__deallocations;
std::free(ptr);
}
size_t __array_deallocations = 0;
void operator delete[](void* ptr) noexcept
{
++__array_deallocations;
std::free(ptr);
}
#include <iostream>
struct EnsureOutput
{
~EnsureOutput()
{
using namespace std;
cout << "Allocations: " << __allocations << endl;
cout << "Deallocations: " << __deallocations << endl;
cout << "Array Allocations: " << __array_allocations << endl;
cout << "Array Deallocations: " << __array_deallocations << endl;
if(__allocations == __deallocations && __array_deallocations == __array_deallocations)
{
cout << "No leaks discovered" << endl;
}
else
{
cout << "You have a memory leak." << endl;
}
}
};
EnsureOutput o = {};