[英]std::string(empty char*) error: basic_string::_S_construct null not valid error
On Debian, I need to read an environment variable, otherwise return an empty string. 在Debian上,我需要读取一个环境变量,否则返回一个空字符串。 Here is my code:
这是我的代码:
std::string getEnv(std::string var)
{
char* val = ::getenv(var.c_str());
std::string retVal(val);
return retVal;
}
When the environment variable is not found, I'm getting the following error: 找不到环境变量时,出现以下错误:
basic_string::_S_construct null not valid error
After debugging, the error code happens on std::string retVal(val)
when I try to load an empty val to it. 调试后,当我尝试向其加载空值时,错误代码会在
std::string retVal(val)
发生。
I tought loading an string from an empty char *
would work, but seens not to. 我可以从一个空的
char *
加载一个字符串,但是可以,但是似乎不行。
How can I fix the above code so that I can make it work in case the enviroment variable does not exists ? 如何修复以上代码,以便在环境变量不存在的情况下可以正常工作?
From man getenv
: 来自
man getenv
:
The
getenv()
function returns a pointer to the value in the environment, orNULL
if there is no match.getenv()
函数返回指向环境中值的指针;如果不匹配,则返回NULL
。
So you need to account for the case where val == NULL
. 因此,您需要考虑
val == NULL
的情况。
std::string getEnv(std::string var)
{
const char* val = ::getenv(var.c_str());
if (val == nullptr)
return std::string("");
return std::string(val);
}
would be a possible solution (return empty string if var is not found). 可能的解决方案(如果未找到var,则返回空字符串)。
you can use string::data() function to get the address of underling buffer pointer. 您可以使用string :: data()函数获取下缓冲指针的地址。
try var.c_str() or var.data(). 尝试var.c_str()或var.data()。
std::string getEnv(std::string var)
{
char* val = ::getenv(var.data());
std::string retVal(val ? val : "");
return retVal;
}
For me its working. 对我来说,它的工作。
val ? val : ""
val ? val : ""
to avoid passing NULL to std::string()
constructor val ? val : ""
避免将NULL传递给std::string()
构造函数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.