B B
B B

Reputation: 13

Direct data into non existing array

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.

Upvotes: 0

Views: 55

Answers (1)

Max Vollmer
Max Vollmer

Reputation: 8598

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);
}

Upvotes: 0

Related Questions