EnumProcesses: program crashes.

Mar 6, 2011 at 12:23am
Hello, why does the program below crash?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <windows.h>
#include <tchar.h>
#include <psapi.h>
#include <iostream>

int main()
{

    DWORD nProcess[1024], bN, bR;
    bN = sizeof(nProcess);
    int NrProcess;

    if(EnumProcesses(nProcess, bN, &bR) != 0)
    {
        std::cout << "EnumProcesses failed: " << GetLastError() << ".\n";
    }
    else
    {
        std::cout << "EnumProcesses has been called!\n";
        NrProcess = (bR/sizeof(DWORD));
        std::cout << "Processes currently running: " << NrProcess << ".\n";
    }

    return 0;
}
Mar 6, 2011 at 3:06am
The Microsoft docs say
If the function succeeds, the return value is nonzero.


bN is incorrect, causing EnumProcess to overwrite parts of the stack.
 
bN = sizeof(nProcess) / sizeof(DWORD);
Mar 6, 2011 at 3:14pm
Thanks.
I changed bN and and 0 to 1 but it still doesn't work.
Last edited on Mar 6, 2011 at 3:17pm
Mar 6, 2011 at 8:13pm
What's the error-code returned by GetLastError?
Mar 6, 2011 at 9:32pm
Nothing, since it crashes.
Mar 6, 2011 at 10:13pm
When does it crash?
Mar 6, 2011 at 10:18pm
You can leave the != part completely out. Nonzero values are true.

Programs that must run on earlier versions of Windows as well as Windows 7 and later versions should always call this function as EnumProcesses. To ensure correct resolution of symbols, add Psapi.lib to the TARGETLIBS macro and compile the program with –DPSAPI_VERSION=1. To use run-time dynamic linking, load Psapi.dll.


Not sure, but might that be a problem?
Mar 7, 2011 at 12:31am
I'm back on Windows. I've just compiled it with my recomended fixes and it works.

I'm not sure what you think NrProcess does, but it's wrong.
Last edited on Mar 7, 2011 at 12:32am
Topic archived. No new replies allowed.