如果从文件中读取,则无法通过Filename运行进程

时间:2014-12-13 12:31:14

标签: c++ winapi

LPCSTR      __FileName = "program.exe";   

void ProcessRun(LPCSTR pszExeName)
    {
        PROCESS_INFORMATION piProcInfoGPS;
        STARTUPINFO siStartupInfo;
        SECURITY_ATTRIBUTES saProcess, saThread;
        ZeroMemory(&siStartupInfo, sizeof(siStartupInfo));
        siStartupInfo.cb = sizeof(siStartupInfo);
        saProcess.nLength = sizeof(saProcess);
        saProcess.lpSecurityDescriptor = NULL;
        saProcess.bInheritHandle = true;
        saThread.nLength = sizeof(saThread);
        saThread.lpSecurityDescriptor = NULL;
        saThread.bInheritHandle = true;

        CreateProcess(NULL, (LPTSTR)pszExeName, &saProcess, &saThread, false, CREATE_DEFAULT_ERROR_MODE, NULL, NULL, &siStartupInfo, &piProcInfoGPS);

        __hProcess = piProcInfoGPS.hProcess;
        __ProcessID = piProcInfoGPS.dwProcessId;
    }

如果我将__FileName传递给函数,程序将运行。 但是,当我从我的ini文件中读取文件名时

[Launcher]
FileName=program.exe


char INIValue[256];
GetPrivateProfileString("Launcher", "FileName", "nan.exe", INIValue, 256, ".\\BackgroundConfig.ini");

string temp(INIValue);
__FileName = temp.c_str();

然后尝试将文件名传递给函数,它不会运行。 世界上是什么造成了这种情况?文件名完全相同。

1 个答案:

答案 0 :(得分:2)

您还没有显示足够的代码来确定这是问题,但请考虑以下因素:

char * someString;

void foo()
{
    std::string str("whatever");
    doSomethingWithCharStar(str.c_str()); // fine: str's data has not been destroyed yet
    someString = str.c_str();
} // uh-oh, here the std::string's memory will be deleted

void bar()
{
    foo(); // sets someString
    doSomethingWithCharStar(someString); // by the time we get here, though, the memory pointed to by someString is freed
}

上面的代码调用未定义的行为(假设doSomethingWithCharStar取消引用传入的指针)。您应该存储char*,而不是将std::string存储为全局。更好的是,根本不使用全球:

std::string foo()
{
    return std::string("whatever");
}

void bar()
{
    std::string value(foo());
    doSomethingWithCharStar(value.c_str());
}

请注意,上面第一个代码段中遇到的问题与Returning a reference to a local variable时的问题基本相同。