存储在LPCSTR中的C ++字符坏了吗?

时间:2013-01-25 14:38:06

标签: c++ string variables lpcstr

LPCSTR dllPath = ExePath().append("\\").append(DEF_INJECT_DLL).c_str();
DWORD dwBufSize = (DWORD)(strlen(dllPath) + 1) * sizeof(LPCSTR);

/* test */

char tbuf[1024]= {0,};
sprintf_s(tbuf, "dllPath : %s\r\ndwBufSize : %d", dllPath, dwBufSize);
MessageBoxA(NULL, tbuf, "TEST", MB_OK);

注入我的dll的部分代码。

ExePath()是使用AbsolutePath API等获取std::string GetModuleFileNameA数据类型的函数。

DEF_INJECT_DLL#define "MyDll.dll"

定义

但是当我运行这段代码时,它会向我显示破碎的字符串......

enter image description here

并且,当我将MessageBoxA更改为此时:

MessageBoxA(NULL,
            ExePath().append("\\").append(DEF_INJECT_DLL).c_str(),
            "TEST",
            MB_OK);

enter image description here

它显示得当吗?

另外,我试着用这种方式:

MessageBoxA(NULL,dllPath, "TEST", MB_OK);

但它向我展示了第一个截图。

有什么问题?

1 个答案:

答案 0 :(得分:3)

问题出在这一行:

LPCSTR dllPath = ExePath().append("\\").append(DEF_INJECT_DLL).c_str();

在这里你调用ExePath(),它返回一个std::string实例,修改它,最后调用c_str()来获取原始数据缓冲区。

但是,返回值是临时对象。在该行之后,将删除返回的std::string,并清除其内存。因此,dllPath指向的地址不再有效!

您可以将返回值存储在本地实例中,例如

std::string str = ExePath().append("\\").append(DEF_INJECT_DLL);
LPCSTR dllPath = str.c_str();