我的代码会导致内存泄漏吗? [英] Will my code cause memory leak?
本文介绍了我的代码会导致内存泄漏吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我下面有这三个函数,会导致内存泄漏,返回后如何删除结果?谢谢.
I have these three functions below, will it cause memory leak, how can I remove the result after return? Thank you.
static vector<string> explode (string original, char exploder)
{
stringstream sstr(original);
vector<string> ret_val;
string buffer = "";
while (getline(sstr, buffer, exploder))
ret_val.push_back(buffer);
return ret_val;
}
static string netstr2cppstr(String ^ s)
{
// convert .NET System::String to string
const char* cstr = (const char*) (Marshal::StringToHGlobalAnsi(s)).ToPointer();
string sstr = cstr;
Marshal::FreeHGlobal(System::IntPtr((void*)cstr));
return sstr;
}
static char *str2char(string s)
{
// string to char array
char * buf;
buf = new char[s.size()+1];
strcpy(buf, s.c_str());
return buf;
}
推荐答案
此处可能引起泄漏的两行是'string sstr = cstr;'. (该字符串构造可能会抛出,因此cstr会泄漏)和'strcpy(buf,s.c_str());' (s.c_str()可能会抛出C ++'03(但不会抛出C ++ 0x),因此buf会泄漏).除此之外,代码 看起来效率很低(尤其是爆炸),但看起来并不危险.
The two lines here that could cause a leak are 'string sstr = cstr;' (that string construction could throw, so cstr would leak) and 'strcpy(buf, s.c_str());' (s.c_str() could throw in C++'03 (but not C++0x), so buf would leak). Other than that, the code looks quite inefficient (explode in particular) but doesn't look dangerous.
这篇关于我的代码会导致内存泄漏吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文