17

In my program I've the following code:

//Code
 if not CreateProcess(nil, NonConstCmd, nil, nil, True, NORMAL_PRIORITY_CLASS or
    CREATE_NEW_PROCESS_GROUP, nil, PCh, SI, P) then
//Code

And I keep getting Access violation error. By the way, in Delphi7 the same code works perfectly. I've read MSDN and found that CreateProcess function in Delphi can modify the second argument. Inititally It was const, that's why I create a new variable with the same value. But it takes no effect.

The question is: why doesn't this code work?

T.S
  • 355
  • 4
  • 18
vralex
  • 251
  • 3
  • 7
  • 4
    Your code looks incomplete, try posting the full code which you are using including the variables types and how you are filling the parameters which you passing to the `CreateProcess` function. – RRUZ Jul 15 '11 at 11:10
  • 2
    The `CreateProcess` invocation can't tell us anything useful. You get the Access Violation because the implementation of `CreateProcess` manages to access invalid memory using one of the pointers you're passing as parameters. In other words, the root problem's in how you prepare the parameters and the type of the parameters. – Cosmin Prund Jul 15 '11 at 11:18
  • -1 for insufficient information – Rob Kennedy Jul 15 '11 at 13:32

1 Answers1

33

The problem is in the lpCommandLine parameter. I suspect you are doing something like this:

var
  CmdLine: string;
...
CmdLine := 'notepad.exe';
CreateProcess(nil, PChar(CmdLine), ...)

This results in an access violation because CmdLine is not writeable memory. The string is a constant string stored in read-only memory.

Instead you can do this:

CmdLine := 'notepad.exe';
UniqueString(CmdLine);
CreateProcess(nil, PChar(CmdLine), ...)

This is enough to make CmdLine be backed by writeable memory.

It is not enough just to make the variable holding the string non-const, you need to make the memory that backs the string writeable too. When you assign a string literal to a string variable, the string variable points at read-only memory.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • Do shellexecute and shellexecuteEx also require the same treatment since i am getting access violation error in Delphi XE for these function calls. I do have a variable path intention i.e. not string literals but changing paths. – user30478 Jun 24 '18 at 20:39
  • 1
    @user No such requirement for those functions. Only ever use ShellExecuteEx though because it reports errors properly. – David Heffernan Jun 24 '18 at 20:55