Possible Duplicate:
How to get memory block length after malloc?
If I have a pointer, is it possible to learn how many bytes were allocated by new
?
When I googled I found a solution for Windows: _msize()
and for Mac: malloc_size()
. But nothing for Linux.
And if not, does anybody know why is it hidden from a programmer? delete
should definitely know such info.
Update:
As far as I know, if I have this code:
class A {
~A() {}
int m_a;
};
class B : public A {
~B() {}
int m_b;
};
int main() { A * b = new B(); delete b; return 0; }
Destructor of A will be called, but still all the memory allocated by new
will be freed.
This means that it can be somehow computed knowing only the pointer. So what is the reason for hiding it from a programmer?
Unfortunately, there is no portable way of obtaining the number of bytes allocated by new
and malloc
. There are a number of reason why this is the case:
delete
and free
do nothing at all. As such, they don't need to store size information. This is surprisingly common in embedded platforms; it lets you use C or C++ code written for other platforms unchanged, as long as you don't do too much allocation.As portable languages, C and C++ can't offer a feature that won't be available (or well-defined, or reasonably fast) on every platform. That's why this is not available on C++. That said, you don't need this - C++ offers std::vector
, which does track the size of your allocation, or std::string
which takes care of all of those details for you.
new
, malloc
, calloc
and all the other heap related allocations in the language (yes, there are many more than those) will allocate at least the amount of memory you requested. They may allocate more (and in general they will allocate more).
There is no portable way to know how much they allocated. In fact there is no way at all unless you know exactly what heap manager you are using.
You also need to distinguish allocated memory in the sense of memory that you may access safely from the returned pointer (that's what malloc_size returns on macs and probably what _msize returns on windows) from actual memory that is 'taken away from the heap' because of the allocation (which includes bookkeeping information which may or may not be adjacent to the memory block you allocated and may or may not be the same for same-sized allocations).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With