Search code examples
c++sizeofalignof

How do I fix "The program issued a command but the command length is incorrect." error when calling Process32First()?


GetLastError tells me I'm getting the "The program issued a command but the command length is incorrect." error when calling Process32First() (see code below). I found one post that looked helpful (http://social.msdn.microsoft.com/Forums/is/vcgeneral/thread/6f43716f-fdd3-4c92-bfba-6a23178c32bf), but I'm not sure if this is my problem.

I've tried building a program that includes only "stdafx.h", <iostream>, <Windows.h> and <TlHelp32.h> to test __alignof(PROCESSENTRY32), but I still get a value of 4. Not sure if that's correct or not.

Here is the code that's failing:

HANDLE hProcess;
PROCESSENTRY32 pe32;

cout << "Size of PROCESSENTRY32 is: " << sizeof(PROCESSENTRY32) << "\r\n"; // 556
cout << "Align of PROCESSENTRY32 is: " << __alignof(PROCESSENTRY32) << "\r\n"; // 4

if ( !(hProcess = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)) ) {
    cout << "CreateToolhelp32Snapshot() failed: " << GetLastError() << "\r\n";
    return (HANDLE)NULL;
} else {
    cout << "CreateToolhelp32Snapshot() succeeded.\r\n";
}

if (Process32First(hProcess, &pe32)) {
    do {
        cout << pe32.th32ModuleID;
    } while (Process32Next(hProcess, &pe32));
} else {
    cout << "Process32First() failed: " << GetLastError() << "\r\n";
}

Solution

  • From the docs on Process32First:

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

    I don't see you doing that in your code, and I suspect it's the problem. Fix it:

    pe32.dwSize = sizeof pe32;
    if (Process32First(...))
    

    The reasoning behind this mandatory action for many of the winapi structures is for the flexibility to add more onto the structure later on, but let functions know which version is being used by checking against known sizes of previous versions.