0

I want to find the number of running processes using EnumProcesses function from psapi library. The function requieres an array that will receive the list of process identifiers. It also writes the total number of bytes of found data into a given variable. I didn't want the process list, just their number. I did the following.

DWORD listSize;
DWORD a;
EnumProcesses( &a, 1000*sizeof(DWORD), &listSize ) ;
listSize/=sizeof(DWORD);
printf("%d",listSize);

This writes the real number of processes into listSize however the program stops working after that. I was wondering if there is a way to immediately send the retrieved data into oblivion and just get the number of it.

B B
  • 13
  • 4
  • Have you actually read [Microsoft's documentation of the `EnumProcesses` library call](https://learn.microsoft.com/en-us/windows/win32/api/psapi/nf-psapi-enumprocesses), and its description of the parameters to the library call? Pop quiz: what should be the first parameter, and what do you actually pass in? – Sam Varshavchik Sep 29 '19 at 22:20
  • @SamVarshavchik I know this is not the proper use of the function. I used the function to point out that I don't want to receive the data, just its size – B B Sep 29 '19 at 22:31
  • Except by using it improperly, this results in undefined behavior, memory corruption, and the crash that you've observed. What did you expect to happen if you give this library function a pointer to just one word, but tell the library function that it's an array of a 1000 words that it is free to write into? – Sam Varshavchik Sep 30 '19 at 01:01

1 Answers1

0

Not possible. However providing a big enough array isn't really much of an issue on modern systems.

I recommend writing a helper function that wraps this all away for you with a dynamically sized container, so you can handle cases where more processes exist than your original array can hold:

DWORD GetNumberOfProcesses()
{
    std::vector<DWORD> processes;
    DWORD size = 0;
    DWORD bytesReturned = 0;
    while (bytesReturned == size)
    {
        size += 1024 * sizeof(DWORD);
        processes.resize(size / sizeof(DWORD));
        if (!EnumProcesses(processes.data(), size, &bytesReturned))
        {
            return -1;
        }
    }
    return bytesReturned / sizeof(DWORD);
}
Max Vollmer
  • 8,412
  • 9
  • 28
  • 43