I would like to define some re-definitions of the new and delete operators in c++ to play a bit around and track memory allocations / freeing, something in this kind:
#include <iostream>
#include <vector>
void* operator new(std::size_t n) {
std::cout << "[Allocate " << n << " bytes]";
void * ptr_out = malloc(n);
std::cout << " at addr " << ptr_out << std::endl;
return ptr_out;
}
void operator delete(void* p) throw() {
std::cout << "[Free 1 byte] at addr " << p << std::endl;
free(p);
}
void operator delete(void* p, std::size_t nbr_bytes) throw() {
std::cout << "[Free " << nbr_bytes << " bytes] at addr " << p << std::endl;
free(p);
}
int main()
{
std::cout << "small vector" << std::endl;
std::vector<int> vec_1 {1, 2, 3, 4};
}
I am able to intercept the memory allocation (new) well, however I do not manage to intercept the memory freeing (delete) in such a way as to show that a whole memory block is released, i.e. I get:
small vector
[Allocate 16 bytes] at addr 0x55b1c5d84280
[Free 1 byte] at addr 0x55b1c5d84280
while really I would want to show that the program released the full 16 bytes of the vector when the program returns.
Any idea if / how I can do this, i.e. print the following instead?
small vector
[Allocate 16 bytes] at addr 0x55b1c5d84280
[Free 16 bytes] at addr 0x55b1c5d84280