Thread: How to detect CPU usage and free RAM on Windows x86 in C?

  1. #1
    Registered User
    Join Date
    Sep 2014
    Posts
    235

    Question How to detect CPU usage and free RAM on Windows x86 in C?

    I don't use Visual Studio and/or C++ so I would like to do it without them. I found this article
    c++ - How to determine CPU and memory consumption from inside a process? - Stack Overflow

    I tried some lines of code but no one works for me.

    Code:
    #include "windows.h"
    
    typedef struct _MEMORYSTATUSEX {
        DWORD dwLength;
        DWORD dwMemoryLoad;
        DWORDLONG ullTotalPhys;
        DWORDLONG ullAvailPhys;
        DWORDLONG ullTotalPageFile;
        DWORDLONG ullAvailPageFile;
        DWORDLONG ullTotalVirtual;
        DWORDLONG ullAvailVirtual;
        DWORDLONG ullAvailExtendedVirtual;
    } MEMORYSTATUSEX, *LPMEMORYSTATUSEX;
    WINBASEAPI
    BOOL
    WINAPI
    GlobalMemoryStatusEx(
        IN OUT LPMEMORYSTATUSEX lpBuffer
        );
    
    
    MEMORYSTATUSEX memInfo;
    DWORDLONG totalPhysMem = memInfo.ullTotalPhys;
    memInfo.dwLength = sizeof MEMORYSTATUSEX;
    GlobalMemoryStatusEx(&memInfo);
    DWORDLONG totalVirtualMem = memInfo.ullTotalPageFile;
    DWORDLONG virtualMemUsed = memInfo.ullTotalPageFile - memInfo.ullAvailPageFile;
    error: initializer element is not constant:
    DWORDLONG totalPhysMem = memInfo.ullTotalPhys;

    error: expected '=', ',', ';', 'asm' or '__attribute__' before '.' token
    memInfo.dwLength = sizeof MEMORYSTATUSEX;

    These was just my first tries to work with da MEMORYSTATUSEX.

    I would like to find out if there is free memory at least ... (some value) and similar.
    Last edited by barracuda; 02-20-2015 at 11:01 AM.

  2. #2
    Registered User
    Join Date
    May 2009
    Posts
    4,183
    Learn what a function is; then put your code in a function.

    Tim S.
    "...a computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are,in short, a perfect match.." Bill Bryson

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 16
    Last Post: 12-28-2012, 04:07 PM
  2. malloc and free usage
    By Dedalus in forum C Programming
    Replies: 3
    Last Post: 09-26-2011, 08:06 AM
  3. Correct usage of malloc and free for 2D array
    By disruptivetech in forum C Programming
    Replies: 1
    Last Post: 10-20-2008, 05:20 AM
  4. How do I detect if windows is shutting down?
    By *Tom* in forum Windows Programming
    Replies: 7
    Last Post: 09-02-2006, 12:01 PM
  5. free() usage
    By pdstatha in forum C Programming
    Replies: 5
    Last Post: 03-13-2002, 09:28 AM