M
ma740988
Consider:
bool transmit ( const char* pch, size_t len )
{
int const val = strcmp( pch, "who_am_i" );
if ( val == 0 )
return ( true );
return ( false );
}
int main ( void )
{
std::stringstream str;
str << "who_am_i";
size_t const sz = str.str().size() ; // the temporary created is
destroyed
char* ftest = new char [ sz + 1 ];
strcpy( ftest, str.str().c_str() );
std::cout << std::hex
<< static_cast<int>(ftest[0])
<< ""
<< static_cast<int>(ftest[1])
<< std::endl;
if ( transmit ( str.str().c_str(), str.str().size()) )
{ std::cout << " success " << std::endl; }
else
{ std::cout << " failure " << std::endl; }
}
At issue:
str.str().c_str().
If I did:
const char* ptr_me = str.str().c_str();
The temporary returned from .str() is destroyed at the end of the full
expression, and it takes the buffer used by .c_str() with it. Not
good.
The question then becomes, where's the end of the full expression for
the case where I call the transmit function. Is that at the
terminating brace of the transmit function?
In my mind the temporary should be destroyed at the opening brace of
transmit but that doesn't appear to be the case.
bool transmit ( const char* pch, size_t len )
{
int const val = strcmp( pch, "who_am_i" );
if ( val == 0 )
return ( true );
return ( false );
}
int main ( void )
{
std::stringstream str;
str << "who_am_i";
size_t const sz = str.str().size() ; // the temporary created is
destroyed
char* ftest = new char [ sz + 1 ];
strcpy( ftest, str.str().c_str() );
std::cout << std::hex
<< static_cast<int>(ftest[0])
<< ""
<< static_cast<int>(ftest[1])
<< std::endl;
if ( transmit ( str.str().c_str(), str.str().size()) )
{ std::cout << " success " << std::endl; }
else
{ std::cout << " failure " << std::endl; }
}
At issue:
str.str().c_str().
If I did:
const char* ptr_me = str.str().c_str();
The temporary returned from .str() is destroyed at the end of the full
expression, and it takes the buffer used by .c_str() with it. Not
good.
The question then becomes, where's the end of the full expression for
the case where I call the transmit function. Is that at the
terminating brace of the transmit function?
In my mind the temporary should be destroyed at the opening brace of
transmit but that doesn't appear to be the case.