使用CreateProcessW新建进程时导致的内存写入错误的解决方案
回答百度知道上网友的问题,和网友一起讨论之后才发现的这一小错误,顺便记录下来。
就因为MSDN中被忽视的这么一小段话:
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.
即CreateProcess的Unicode版函数CreateProcessW会修改其参数lpCommandLine所指向的字符串。因此这个参数不能指向只读内存(比如字符串常量),如果该参数是字符串常量,会导致内存访问异常。
可以看出CreateProcess和CreateProcessW存在一些差异。
因为新版的Visual Studio会将vc创建的项目默认使用Unicode编码的字符串,对应的函数也会使用Unicode版的,比如这里的CreateProcessW。
有这样的一段代码,在vc 2008下会出错:
#include <windows.h>
#include <tchar.h>
int _tmain(int argc, _TCHAR* argv[])
{
STARTUPINFOW si={sizeof(si)};
wchar_t *sz_CommandLine=L"notepad";
PROCESS_INFORMATION pi;
::CreateProcessW(NULL,sz_CommandLine,NULL,NULL,FALSE,NULL,NULL,NULL,&si,&pi);
return 0;
}
需要做如下修改:
#include <windows.h>
#include <tchar.h>
int _tmain(int argc, _TCHAR* argv[])
{
STARTUPINFOW si={sizeof(si)};
wchar_t *sz_CommandLine=L"notepad";
TCHAR temp[255] = {0};
_tcscpy(temp,sz_CommandLine);
PROCESS_INFORMATION pi;
::CreateProcessW(NULL,temp,NULL,NULL,FALSE,NULL,NULL,NULL,&si,&pi);
return 0;
}