F
Fab
Hi C++ experts,
I'm using std:stringstream in my program to format a string. In my
unit tests I use it quite extensively to generate expected results
that I then compare with a predefined string.
The problem is that this code does something wrong:
std:stringstream os;
os << "Hello world";
const char * const produced = os.str().c_str();
if (strcmp(produced, "Hello world") == 0) {...}
In particular, the 'produced' buffer is invalid.
On Linux and Mac OS X the program run and any access to 'produced'
buffer, does not report any error, but if you run a test program with
valgrind, Guard Malloc or any other memory checker tools, all the
tools report some problems.
The workaround to this problem is to generate a temporary variable to
store a reference to the the std::string produced by os.str(). In this
case everything works as expected:
std:stringstream os;
os << "Hello world";
const std::string & tempString(os.str());
const char * const produced = os.str().c_str();
if (strcmp(produced, "Hello world") == 0) {...}
Is it because os.str().c_str() generates a temporary std::string to
store the produced string, and c_str() returns a pointer to this temp
object? Shouldn't temp object get disposed when exiting the scope?
Does it mean that this temp string's scope is only the 'produced'
assignment and after that is no longer valid?
What's your opinion on that?
F.
I'm using std:stringstream in my program to format a string. In my
unit tests I use it quite extensively to generate expected results
that I then compare with a predefined string.
The problem is that this code does something wrong:
std:stringstream os;
os << "Hello world";
const char * const produced = os.str().c_str();
if (strcmp(produced, "Hello world") == 0) {...}
In particular, the 'produced' buffer is invalid.
On Linux and Mac OS X the program run and any access to 'produced'
buffer, does not report any error, but if you run a test program with
valgrind, Guard Malloc or any other memory checker tools, all the
tools report some problems.
The workaround to this problem is to generate a temporary variable to
store a reference to the the std::string produced by os.str(). In this
case everything works as expected:
std:stringstream os;
os << "Hello world";
const std::string & tempString(os.str());
const char * const produced = os.str().c_str();
if (strcmp(produced, "Hello world") == 0) {...}
Is it because os.str().c_str() generates a temporary std::string to
store the produced string, and c_str() returns a pointer to this temp
object? Shouldn't temp object get disposed when exiting the scope?
Does it mean that this temp string's scope is only the 'produced'
assignment and after that is no longer valid?
What's your opinion on that?
F.