0

I work with WinAPI and I have a function that creates a new process:

void new_process() {
    STARTUPINFO si = { sizeof(si) };
    PROCESS_INFORMATION pi;
    TCHAR szCommandLine[] = TEXT("NOTEPAD");
    CreateProcess(NULL, szCommandLine, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
}

But when I call this function from main(), it's doesn't work:

void new_process(TCHAR szCommandLine[]) {
    STARTUPINFO si = { sizeof(si) };
    PROCESS_INFORMATION pi;
    CreateProcess(NULL, szCommandLine, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
}

int _tmain(int argc, _TCHAR* argv[]) {
    new_process(TEXT("NOTEPAD"));
    return 0;
}

Where is my mistake?

rel1x
  • 2,351
  • 4
  • 34
  • 62

1 Answers1

3

The problem is explained here. MSDN says -

The Unicode version of this function, CreateProcessW, can modify the contents of this string. Therefore, this parameter cannot be a pointer to read-only memory (such as a const variable or a literal string). If this parameter is a constant string, the function may cause an access violation.

When you pass TEXT("NOTEPAD") as the parameter to the function new_process(TCHAR szCommandLine[]) which in turn passes this as the lpCommandLine parameter to the CreateProcess() API, it will try to modify this location as quoted from MSDN above.

Since the parameter TEXT("NOTEPAD") is a CONSTANT memory, when the CreateProcess() tries to modify this memory as quoted above, it will cause memory access violation.

So ideally you should call the function new_process(TCHAR szCommandLine[]) from the main() function as given below.

TCHAR APP_NAME[] = TEXT("NOTEPAD");   
new_process(APP_NAME);

Hope this help!

MNS
  • 1,354
  • 15
  • 26