Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ERROR_BAD_LENGTH when calling Process32First in Windows 7

Tags:

c++

windows-7

I just tried to revoke some old code from Windows XP which generates a list of all running processes, but it failed on Windows 7. Before I continue, here's the code:

#include <windows.h>
#include <tlhelp32.h>

int main()
{
    HANDLE hSnap, hTemp;
    PROCESSENTRY32 pe;

    hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);

    if(Process32First(hSnap, &pe)) {
        do {
            ...
            }
        } while(Process32Next(hSnap, &pe));
    }
    ...
}

I checked which function failed and it turned out that it's Process32First. GetLastError() returned 24: "ERROR_BAD_LENGTH" I can't really figure out what the problem is. Any suggestions?

like image 346
Process First Avatar asked Jun 29 '11 13:06

Process First


2 Answers

From MSDN: http://msdn.microsoft.com/en-us/library/ms684834(VS.85).aspx

The calling application must set the dwSize member of PROCESSENTRY32 to the size, in bytes, of the structure.

To retrieve information about other processes recorded in the same snapshot, use the Process32Next function.


EDIT: You'd probably want to do something like this:

PROCESSENTRY32 pe = {0};
pe.dwSize = sizeof(PROCESSENTRY32);
like image 76
jglouie Avatar answered Nov 13 '22 12:11

jglouie


There's a bug in tlhelp32.h, when invoked in WIN64:

If there's a #pragma pack directive somewhere before including tlhelp32.h, it will generate a PROCESSENTRY32 structure with the wrong size. Then anything can happen, including Process32First failures, or even crashes.

Try including tlhelp32.h this way:

 #pragma pack(push,8) /* Work around a bug in tlhelp32.h in WIN64, which generates the wrong structure if packing has been changed */<br/>
 #include &lt;tlhelp32.h&gt;<br/>
 #pragma pack(pop)
like image 3
Jean-François Larvoire Avatar answered Nov 13 '22 13:11

Jean-François Larvoire