所以,我有一个lib文件,其中有将字符串转换为char *的函数:
void Additional::str2Char(string s,char** cstr)
{
*cstr = new char[s.length() + 1];
*cstr = (char*) s.c_str();
}
然后,我创建控制台应用程序,并执行以下操作:
int main()
{
Additional *a = new Additional();
string b = "fdfd";
char *test;
a->str2Char(b, &test);
cout << test << endl;
delete a;
}
输出确实很糟糕。.帮助我,我不知道如何正确地从lib中获取指针。
首先,您分配一些内存。
然后,您将指针重新分配给该内存,以指向本地字符串的内容,从而s
泄漏您分配的内存。
然后,您从函数中返回,销毁s
,使指针悬空。它不再指向有效数据,并且对其取消引用将产生未定义的行为。
最好的解决方案是停止弄乱指针和new
,并将其std::string
用于所有字符串。如果您确实想这样做,则需要将字符串内容复制到新的内存中:
*cstr = new char[s.length() + 1]; // no change
std::strcpy(*cstr, s.c_str()); // copy the data, including the terminator
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句