Zorglub29
Zorglub29

Reputation: 8899

redefining new and delete operators in cpp for tracking memory allocations: cannot track size of delete of whole memory blocks

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

Upvotes: 1

Views: 661

Answers (1)

Asteroids With Wings
Asteroids With Wings

Reputation: 17464

It is implementation-defined as to which of those operator delete overloads will be called when deleting objects of incomplete type and arrays of non-class and trivially-destructible class types (ref1, ref2).

Vector is probably allocating chars or similar, so you're subject to this rule.

You can use the nbr_bytes argument to be more efficient if you get given it, but you'll have to store the information yourself if you want guaranteed access to it.

If you use a std::map to do so, be careful that you don't write yourself into a recursive disaster 😜.

Upvotes: 2

Related Questions