Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Violation in function CreateProcess in Delphi 2009

Tags:

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?

like image 802
vralex Avatar asked Jul 15 '11 10:07

vralex


1 Answers

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.

like image 89
David Heffernan Avatar answered Oct 25 '22 22:10

David Heffernan