cpp 检查抱怨危险使用 c_str(). c_str() 返回的值在本次调用后无效,如何解决?

cpp check complains dangerous use of c_str(). the value returned by c_str() is invalid after this call , how to solve this?

本文关键字:str 无效 调用 解决 何解决 危险 检查 cpp 返回      更新时间:2023-10-16
if(ini_getstr(getname("hello"))) //this is the getname function call
char* ini_getstr(char * key) { //some code }
char* getname(std::string name) //need to return char* 
{ 
std::string ininame("name"); 
ininame.append(":"+name); 
return (*char)ininame.c_str();//cpp check complains dangerous use of c_str().
}

您的函数将无法正常工作,因为它返回指向存储在ininame对象内部的数据的指针,但由于ininame是局部变量,因此当函数返回时它会被销毁,使调用代码保留指向不再有效的数据的指针。

执行所需操作的正确方法是返回 std::string:

std::string getname(std::string name)
{
std::string ininame("name");
ininame.append(":"+name);
return ininame;
}

。然后,如果需要,调用代码可以在返回的对象上调用 c_str((:

std::string myStr = getname("blah");
printf("The string was %sn", myStr.c_str());

std::string 拥有为字符串分配的内存。所以看这里:

char* getname(std::string name) 
{ 
std::string ininame("name"); 
ininame.append(":"+name); 
// ininame is a temporary variable that exists within the scope of this method.
// once the return has been completed, ininame (and the memory it owns) will 
// be destroyed. So whilst the pointer is valid when c_str() is called here,
// the memory it's pointing to will be deleted as soon as return has completed.
// this isn't safe!
return (*char)ininame.c_str();
}

你最好只返回字符串(因为字符串对象不会删除内存(

std::string getname(std::string name)
{ 
std::string ininame("name"); 
ininame.append(":"+name); 
return ininame;
}

如果无法更改getName函数签名,则可以使用strdup函数。strdup返回指向以 null 结尾的字节字符串的指针,该字符串是指向的字符串的副本。

char* getname(std::string name) //need to return char* 
{ 
std::string ininame("name"); 
ininame.append(":"+name); 
return strdup(ininame.c_str());//cpp check complains dangerous use of c_str().
}

但请记住

返回的指针必须传递给 free,以避免内存泄漏。