I want to convert a process pid to a const char* but below does not work:
std::ostringstream str_pid;
str_pid << getpid();
const char * cstr_pid = str_pid.str().c_str();
It works most of the time but sometimes it has a false result. Apparently i am doing something wrong. Any idea?
cstr_pid
will be a dangling pointer, as the temporary std::string
returned by str_pid.str()
is destructed after the assignment of cstr_pid
. Create a copy of the str_pid.str()
return value:
const std::string my_pid(str_pid.str());
then use my_pid.c_str()
when const char*
is required.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.