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
newandmalloc. There are a number of reason why this is the case:deleteandfreedo 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, orstd::stringwhich takes care of all of those details for you.