CreateProcess causes Access Violation

 CreateProcess causes Access Violation

Published at  Jan 17 2010, 11:39 AM by  pavely |  4 comment(s) 

The famous CreateProcess function may fail with an access violation. For example, this innocent looking code causes a crash:

STARTUPINFO si = { sizeof(si) };

PROCESS_INFORMATION pi;

 

CreateProcess(0, _T("notepad"), 0, 0, FALSE,

    0, 0, 0, &si, &pi);

 

What’s wrong with this code? Apparently nothing.

The key here is that CreateProcess is not actually a function at all, but a macro that’s expanded toCreateProcessA or CreateProcessW depending a compile time constant (UNICODE).

If we open the docs, we find for the second argument: “The Unicode version of this function,CreateProcessW, can modify the contents of this string”.

The string I passed is a constant string, coming from a region marked as “read only” and this is why the access violation occurs. Changing CreateProcess to CreateProcessA avoids the crash. The reason is that the A function translates the string to unicode and calls the W function. The translated string is in a read/write buffer, so no problem there. This should generally be avoided because of the extra step A functions do.

In recent versions of Visual Studio the default libraries are unicode (as they should be, as the Windows 9x family of OSes is finally dead and buried). This is while a transition from (e.g.) Visual Studio 2003 to 2008 may cause old code to crash.

So, the general solution should be:

TCHAR name[] = _T("Notepad.exe");

CreateProcess(0, name, 0, 0, FALSE, 0, 0, 0, &si, &pi);

This still doesn’t answer the question: why? Why would CreateProcessW want to write back to the supplied string? What could it possibly write? It can’t write arbitrary stuff as the size of the buffer is unknown to the function and can cause access violation or memory corruption. But it does write something back (looks like the same string passed to it). For me, it’s still a mystery.

Comments List

# re: Gotcha: CreateProcess causes Access Violation

Published at Sunday, March 28, 2010 10:21 PM by  Sasha Goldshtein  

This topic has been beaten to death with a club by Raymond Chen:

blogs.msdn.com/.../9673254.aspx

# re: Gotcha: CreateProcess causes Access Violation

Published at Sunday, March 28, 2010 10:40 PM by  pavely  

I guess I'm behind the times...

# re: Gotcha: CreateProcess causes Access Violation

Published at Tuesday, April 20, 2010 4:54 AM by mmxida  

Thanks, that's really helpful!

# re: Gotcha: CreateProcess causes Access Violation

Published at Monday, January 23, 2012 2:46 PM by Raj Kumar  

Thanks . its perfectly working fine and helped.

Leave a Comment

Title  (required)
Name  (
required
)

猜你喜欢

转载自cppmule.iteye.com/blog/1609252
今日推荐