Reputation: 737
Ok guys so my goal is track the memory that has been allocated. In order to do so I created a static variable and overloaded new and delete operators. I'm bit confused though. When I create new int object it allocates 4 bytes of memory, however when I delete the pointer to this int it says that 8 bytes has been deleted. Is there a way to track it accurately? Further down the road I would also like to track dynamically created objects and track how much memory has been used for it. Here is my code:
#include<iostream>
#include<stdlib.h>
static int memory{0};
void* operator new(std::size_t sz){
memory+= sz;
return std::malloc(sz);
}
void operator delete(void* ptr) noexcept{
memory-= sizeof(ptr);
std::free(ptr);
}
int main()
{
int * p = new int;
*p = 2;
std::cout << memory; // memory = 4
delete p;
std::cout << memory; // memory = -4
}
Upvotes: 1
Views: 1153
Reputation: 179789
A bit annoying, isn't it? free
knows how much memory there is to free, but won't tell you.
The practical solution is to add an extra sizeof(size_t)
to the malloc
request, and use those first bytes of the returned allocation to store sz
. In operator delete
, you do the reverse: you look for the sizeof(size_t)
bytes preceding ptr
.
So the bit of code you'd get is memory-=static_cast<size_t*>(prt)[-1];
. The [-1]
looks scary, I know. One of the few cases where it makes sense.
Upvotes: 5
Reputation: 22176
You have a wrong assumption here. sizeof
pointer return size of a pointer, not size of structure to which it points to. So, no matter what type of structure you allocated (no matter if it's int
, an instance of a class or an array), you always subtract the same amount of memory.
You should check size of the structure to which pointer points to, but it's quite hard in this code. Since you pass void*
as the argument, you can't dereference it, and you have to idea what type is that pointer.
I suppose you could try with template function to retain pointer type (and be able to dereference it).
Upvotes: -1