ERROR_BAD_LENGTH when calling Process32First in Windows 7

会有一股神秘感。 提交于 2019-12-10 13:38:09

问题


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?


回答1:


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



回答2:


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)


来源:https://stackoverflow.com/questions/6521778/error-bad-length-when-calling-process32first-in-windows-7

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!