Unhandled Error with CreateProcess

access-violation, c++, createprocess, unhandled-exception, winapi

Solution

The problem is that the second parameter of the CreateProcess function is an in/out parameter.

If you specify it as a string like you did, it is a constant string and the function when it is called cannot write to the memory location, thus you have a memory access violation. The correct way is to call your function like this:

LPTSTR szCmdline = _tcsdup(TEXT("C:\\Windows\\Notepad.exe"));

//create child process
if (!CreateProcess(NULL,
    szCmdline,
    NULL,
    NULL,
    FALSE,
    0,
    NULL,
    NULL,
    &si,
    &pi))
{
    fprintf(stderr, "create process failed");

    return -1;
}

You may also want to read this blog article.

Problem

I was reading about CreateProcess function in c++ and I wanted to try it. Basic idea of the code is to have my main execute another process (notepad). Really, it’s just the basic code. When I run the program, I get: First-chance exception at 0x752bb763 in createprocess.exe: 0xC0000005: Access violation writing location 0x00be57b8. Unhandled exception at 0x752bb763 in createprocess.exe: 0xC0000005: Access violation writing location 0x00be57b8. When I make a break point for where the error occurs, I get taken to tidtable.c (which is for accessing threads, I guess). Specifically in tidtable.c at `CRTIMP PFLS_GETVALUE_FUNCTION __cdecl __set_flsgetvalue()` I really don’t know what or how to avoid this problem. The error occurs with the CreateProcess call (ie, it never outputs the “out of create”). My code is: ``` #include "stdafx.h" #include <stdio.h> #include <windows.h> #include <strsafe.h> #include <direct.h> #include <string.h> #include <conio.h> int main(VOID) { STARTUPINFO si; PROCESS_INFORMATION pi; //allocate memory ZeroMemory(&si, sizeof(si)); si.cb = sizeof(si); ZeroMemory(&pi, sizeof(pi)); fprintf(stderr, "This is just a test"); //create child process if (!CreateProcess(NULL, L"C:\\Windows\\Notepad.exe", NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) { fprintf(stderr, "create process failed"); return -1; } fprintf(stderr, "out of create"); //parent waits for child to complete WaitForSingleObject(pi.hProcess, INFINITE); fprintf(stderr, "after wait"); printf("Child Complete"); //close handle CloseHandle(pi.hProcess); // CloseHandle(pi.hthread); } ``` If anyone knows how to overcome this problem, your help would be appreciated.

Original source

Related problems