4
#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;
}

这段代码可以正常工作,没有任何错误泄漏。但我希望能够获得对象的大小。void*我想有一种方法,因为 delete 语句知道对象 v1 指向的大小,以便它可以删除它,因此必须存储它某处。

4

3 回答 3

5

Applying delete to a void * pointer in C++ is illegal.

If your compiler supports this as a non-standard extension, then most likely delete assumes that the unknown object pointed by that pointer has trivial destructor. In that case delete does not have to do anything besides immediately handing over the control to the raw-memory deallocation function ::operator delete, which probably just calls free. (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 msize function. 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 by new and/or what exactly delete v1 does, since it is not standard C++.

于 2012-07-22T06:00:57.497 回答
0

在进行 from double *to的转换时,void *您会丢弃编译器要处理的信息。

因此编译器不知道要调用什么析构函数或对象的大小。

于 2012-07-22T06:12:39.653 回答
0

的大小void *将继续是sizeof一个指针。如果您想找出void *指向的对象的实际大小,您应该知道实际对象并将指针类型转换为正确的类型。不,delete 不会知道对象指针的大小,会导致泄漏。正确的做法delete是确保将指针类型转换为正确的类型。

于 2012-07-22T05:36:11.530 回答