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?
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,以避免内存泄漏。
相关文章:
- Openssl 1.1.1d无效使用不完整的类型"struct dsa_st"
- 无法访问嵌套类.类的使用无效
- 如果用户输入无效,如何使用字符串变量-C++重复输入命令
- 如何解决错误:SCIP C++中的 SCIP 阶段无效 <10>
- Python str to C++ to Python str
- 在没有参数列表的情况下使用模板名称"Event"无效,模板问题
- FFMPEG配置文件级别id大小无效
- 错误:从"int"到枚举c++的转换无效
- 如何修复此错误:className::className的无效使用
- 为什么将值返回函数传递给重载=运算符对运算符函数有效,而对其他运算符无效
- C++-模板嵌套类的引用初始化无效
- 错误:无效的预处理指令 #i 的意思是 #if?
- 多维数组 C++ 中数组下标的类型"int[int]"无效
- 在 C++ 中使用正则表达式错误时出现问题 括号表达式中的范围无效
- 从 'int' 到 'int*' CPP 的转换无效
- 如何接受 [ENTER] 键作为无效输入并发送错误消息
- 为什么无论你输入什么,这"while(cin.get(str,3))"只运行一次?
- 由于无效的 ValidateRgn() 子窗口不会收到WM_PAINT消息
- C++ PTHREADS - 无效转换无效*(*)()到无效*(*)(无效*)
- 从"char"到"const char*"的转换无效 [-fpermissive] str::atoi (字符串到整数)