hi friends,

I want to calculate the amount of heap memory at runtime at any point in
the program.

how do I do this?? do we have a function for it.

Thanks,
himanshu k.
symbian application developer

Recommended Answers

All 5 Replies

Strictly speaking, Windows heap (link in the previous post) is not the same thing as CRT heap. Visual C++ includes (via <malloc.h>) special routine(s) to get heap info (see MSDN for details).
Try:

#include <malloc.h>
/// returns used heap size in bytes or negative if heap is corrupted.
long HeapUsed()
{
    _HEAPINFO info = { 0, 0, 0 };
    long used = 0;
    int rc;

    while ((rc=_heapwalk(&info)) == _HEAPOK)
    {
        if (info._useflag == _USEDENTRY)
            used += info._size;
        }
    if (rc != _HEAPEND && rc != _HEAPEMPTY)
        used = (used?-used:-1);

    return used;
}

See VC++ help for more _heapwalk/_HEAPINFO details (unused or corrupted heap blocks etc).

Of course, no standard C or C++ low level interface to heap management stuff...

That code snippet might tell you how much heap has been used but not how much is available for use. The way I understand it, the max meap available for use is the amount of RAM + free hard drive size (swap space on the hard drive(s))

> Windows heap is not the same thing as CRT heap

and to complicate matters, there may be several win32 heaps (and several CRT heaps) in a process.
if an exe or shared object (DLL) is linked with the static C/C++ runtime library, then the module has its own private copy of the C/C++ runtime (and its own private CRT heap).
even if you link all modules with the DLL version of the C/C++ runtime library, there may not be an agreement across modules on which version of the C/C++ runtime (MSVCRT??.DLL) to use. GetProcessHeaps retrieves handles to all of the heaps that are there in the process. and you would have to do a HeapWalk (win32) / _heapwalk (CRT) on each of them.

To Ancient Dragon: Yes, you right. But I think, RAM and/or max swap file size(s) are (nearly) useless values in practice (especially for ordinary applications in common multiprogramming environments).
So used RTL heap size is (IMHO) the only sensitive parameter.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.