Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrong result from GlobalMemoryStatusEx() on Windows

Tags:

winapi

I'm trying to get total system memory using GlobalMemoryStatusEx():

    MEMORYSTATUSEX memory;
    GlobalMemoryStatusEx(&memory);
#define PRINT(v) {printf("%s ~%.3fGB\n", (#v), ((double)v)/(1024.*1024.*1024.));}
    PRINT(memory.ullAvailPhys);
    PRINT(memory.ullTotalPhys);
    PRINT(memory.ullTotalVirtual);
    PRINT(memory.ullAvailPageFile);
    PRINT(memory.ullTotalPageFile);
#undef PRINT
    fflush(stdout);

But the result is very weired and not understandable.

memory.ullAvailPhys ~1.002GB
memory.ullTotalPhys ~1.002GB
memory.ullTotalVirtual ~0.154GB
memory.ullAvailPageFile ~0.002GB
memory.ullTotalPageFile ~1.002GB

My total physical memory is 8GB but non of result is close it. All values are much smaller.

Also, the 'total' values keep changing whenever I execute. For instance, another result is here:

memory.ullAvailPhys ~0.979GB
memory.ullTotalPhys ~0.979GB
memory.ullTotalVirtual ~0.154GB
memory.ullAvailPageFile ~0.002GB
memory.ullTotalPageFile ~0.979GB

What am I doing wrong?

like image 890
xylosper Avatar asked Feb 14 '15 11:02

xylosper


1 Answers

This is the part you are missing:

MEMORYSTATUSEX memory = { sizeof memory };

MSDN:

dwLength The size of the structure, in bytes. You must set this member before calling GlobalMemoryStatusEx.

If you checked value returned by GlobalMemoryStatusEx, you could see the problem by getting error indication there.

like image 91
Roman R. Avatar answered Nov 17 '22 12:11

Roman R.