执行CreateProcess报非法访问

程序调用CreateProcess总是报非法访问,类似这样调用:

BOOL fSuccess = CreateProcess(NULL, command, NULL, NULL, TRUE, CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi);

 

调了半天不知道什么原因,看command等参数也是正确的,最后无意间将第二个参数lpCommandLine利用strdup进行了内存分配,居然正常了。惊喜之余,想起了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.

由于我的工程是Unicode的,这段话的意思是说,如果是Unicode,该接口可能会修改字符串内容,因此,这个参数如果是只读内存的指针(例如:const变量或字面值常量),可能会引起内存非法访问。看到这里突然就明白了,因为我传入的是字面值常量(调试用的),才会导致这样的问题。

再次重申一点,做Windows开发,遇到问题一定要先查看MSDN,毕竟是微软提供的专业的资料。

附MSDN截图:

 

posted @ 2022-04-16 02:09  快雪  阅读(74)  评论(0编辑  收藏  举报