Search code examples
c++windowsfilecreateprocess

Why does CreateProcessW give a error of 0x2


Im trying to create a debug process using CreateProcessW but it keeps giving me the error 0x2. I checked the error and the real error message is ERROR_FILE_NOT_FOUND. I have checked that the file is there but it still gives me the same error. I am trying to open notepad.

#include <Windows.h>
#include <iostream>

int main()
{
    const char* debugee_path = "C:\\WINDOWS\\system32\\notepad.exe";
    STARTUPINFOW startup_info = {};
    startup_info.cb = sizeof(STARTUPINFOW);

    PROCESS_INFORMATION process_information = {};

    BOOL success = CreateProcessW(
        reinterpret_cast<const WCHAR*>(debugee_path),
        NULL,
        NULL,
        NULL,
        FALSE,
        0,
        NULL,
        NULL,
        &startup_info,
        &process_information
    );
    if (!success)
    {
        return 1;
    }

    return 0;
}

Solution

  • This is the problem: reinterpret_cast<const WCHAR*>(debugee_path). You are interpreting an ASCII string (1 byte per character) as a wchar string (2 bytes per character) which it is not.

    To avoid this kind of mistakes don't use reinterpret_cast. Ever!

    This should work:

    const WCHAR* debugee_path = L"C:\\WINDOWS\\system32\\notepad.exe";
    //                          ^
    //                          |
    //                          note the L prefix on the string literal
    

    Or, as pointed by Remy Lebeau

    use CreateProcessA instead