Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use GetProcessMemoryInfo in C++?

I'm trying to use the function GetProcessMemoryInfo of psapi.h inside a C++ application on Windows 7 32-bit.

I followed some tutorial and I did something like:

PPROCESS_MEMORY_COUNTERS pMemCountr;

pMemCountr = new PROCESS_MEMORY_COUNTERS();
bool result = GetProcessMemoryInfo(GetCurrentProcess(),
                                   pMemCountr,
                                   sizeof(PPROCESS_MEMORY_COUNTERS));

The problem is that i always obtain "false" from the execution of the GetProcessMemoryInfo() method. What am I doing wrong here?

like image 872
Aslan986 Avatar asked Dec 27 '11 11:12

Aslan986


3 Answers

The problem is

sizeof(PPROCESS_MEMORY_COUNTERS)

yields the size of PPROCESS_MEMORY_COUNTERS which is a PROCESS_MEMORY_COUNTERS* type pointer (note double P in the beginning).

What you want is

sizeof(PROCESS_MEMORY_COUNTERS)

Also you'll be much better off without new here:

PROCESS_MEMORY_COUNTERS memCounter;
BOOL result = GetProcessMemoryInfo(GetCurrentProcess(),
                                   &memCounter,
                                   sizeof( memCounter ));
like image 143
sharptooth Avatar answered Nov 05 '22 22:11

sharptooth


change sizeof(PPROCESS_MEMORY_COUNTERS) to sizeof(PROCESS_MEMORY_COUNTERS)

like image 40
marcinj Avatar answered Nov 05 '22 22:11

marcinj


On MSDN:

BOOL WINAPI GetProcessMemoryInfo( In HANDLE Process, Out PPROCESS_MEMORY_COUNTERS ppsmemCounters, In DWORD cb );

Example:

HANDLE hProcess;
PROCESS_MEMORY_COUNTERS pmc;

printf( "\nProcess ID: %u\n", processID );

// Print information about the memory usage of the process.
hProcess = OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processID );
if (NULL == hProcess)
    return;

if (GetProcessMemoryInfo( ( hProcess, &pmc, sizeof(pmc)))
{
    printf( "\tWorkingSetSize: 0x%08X - %u\n",  pmc.WorkingSetSize,  
                                              pmc.WorkingSetSize / 1024);        
    printf( "\tQuotaPeakPagedPoolUsage: 0x%08X - %u\n", 
         pmc.QuotaPeakPagedPoolUsage ,   pmc.QuotaPeakPagedPoolUsage / 1024);
    printf( "\tQuotaPagedPoolUsage: 0x%08X - %u\n", pmc.QuotaPagedPoolUsage, 
                                              pmc.QuotaPagedPoolUsage / 1024);
    printf( "\tQuotaPeakNonPagedPoolUsage: 0x%08X - %u\n", 
               pmc.QuotaPeakNonPagedPoolUsage,pmc.QuotaPeakNonPagedPoolUsage / 1024 );
    printf( "\tQuotaNonPagedPoolUsage:0x%08X-%u\n",pmc.QuotaNonPagedPoolUsage ,   pmc.QuotaNonPagedPoolUsage / 1024);
    printf( "\tPagefileUsage: 0x%08X - %u\n", pmc.PagefileUsage,     pmc.PagefileUsage/1024 ); 
    printf( "\tPeakPagefileUsage: 0x%08X - %u\n", pmc.PeakPagefileUsage, pmc.PeakPagefileUsage/1024 );
    printf( "\tcb: 0x%08X - %u\n", pmc.cb , pmc.cb / 1024);     
}
CloseHandle(hProcess);

Or You can view full code from here

like image 32
Zidane Avatar answered Nov 05 '22 21:11

Zidane