#define BOOST_TEST_MODULE MemoryLeakTest
#include <boost/test/unit_test.hpp>
#include <iostream>
using namespace std;
BOOST_AUTO_TEST_CASE( MemoryLeakTest)
{
double* n1 = new double(100);
void* v1 = n1;
cout << sizeof(v1) << endl;
delete v1;
}
This code will work perfectly fine without any error leaks. But I would like to be able to get the size of the object void* is holding on to.I would imagine there is a way because the delete statement knew how large the object v1 was pointing to so that it can delete it so it must be stored some where.
Applying
deleteto avoid *pointer in C++ is illegal.If your compiler supports this as a non-standard extension, then most likely
deleteassumes that the unknown object pointed by that pointer has trivial destructor. In that casedeletedoes not have to do anything besides immediately handing over the control to the raw-memory deallocation function::operator delete, which probably just callsfree. (This last bit, of course, can depend on the implementation).So, your question basically boils down to “how to determine the size of
malloc-ed memory block”. There’s no standard features that can do that. Either memorize the size yourself, when you allocate it. Or use the non-standard implementation-specific library features, if any such features are provided by your platform.In some implementations this can be done through
msizefunction. But again, in order to do it meaningfully, you’d have to research your implementation first. You need to figure out how the memory is allocated bynewand/or what exactlydelete v1does, since it is not standard C++.