0

I have the following function, written in C++ using WinAPI: The function receives a handle to a process, and should return the size of the memory used by the process.

DWORD GetProcessCommitedMemorySize(const HANDLE hProcess)
{
    MEMORY_BASIC_INFORMATION mbi;
    DWORD totalMemory = 0;
    DWORD currAddr = 0;

    //for checking repetion of pages base addresses
    std::unordered_set<DWORD> tempAddresses;

    while (VirtualQueryEx(hProcess, (LPVOID)currAddr, &mbi, (SIZE_T)sizeof(mbi)) == (SIZE_T)sizeof(mbi))
    {

        if (tempAddresses.find((DWORD)mbi.BaseAddress) == tempAddresses.end()) // not found
        {
            currAddr = (DWORD)mbi.BaseAddress + mbi.RegionSize;
            tempAddresses.insert((DWORD)mbi.BaseAddress);

            if (mbi.State == MEM_COMMIT && mbi.Type == MEM_PRIVATE)
            {
                totalMemory += mbi.RegionSize;

            }
        }
        else
        {
            break;
        }
    }

    return totalMemory;
}

The function always returns a number which is bigger than the amount of memory which is shown to be used on the 'details' page of the Task Manager. for example, 86155 KB as the function's output, and 56924 KB on the Task Manager.

The program still isn't complete so I need to hard-code the PID, so I know I'm looking at the right one.

Does this issue occur because the number I'm seeking with this function and the number on the Task Manager have different meanings, or is my code just not doing what's it supposed to do?

Thanks.

Noam Patai
  • 21
  • 6
  • 2
    Use `GetProcessMemoryInfo` (https://learn.microsoft.com/en-us/windows/win32/api/psapi/nf-psapi-getprocessmemoryinfo) with `PROCESS_MEMORY_COUNTERS_EX`. – Mike Vine Jan 23 '23 at 20:34
  • Virtual memory can do nifty things like ring buffers where the same range of physical memory has two virtual address mappings (so where the ring wraps around, you can still read whatever is stored inside crossing the end as a contiguous object) If you just add up the size of virtual mappings, it will exceed the actual memory used by those mappings. – Ben Voigt Jan 23 '23 at 21:15
  • 1
    https://stackoverflow.com/a/42986966/6401656 – RbMm Jan 23 '23 at 21:57
  • @MikeVine, What value should I check for in the PROCESS_MEMORYCOUNTERS_EX? I assumed you were aiming for the `PrivateUsage` value, as this is the only difference between the two versions of the `PROCESS_MEMORY_COUNTERS` struct. But, this doesn't seem to be right. Thanks for your guidance. – Noam Patai Jan 23 '23 at 22:09

0 Answers0