std::string, C strings and c_str()

From: Anand Hariharan (mailto.anand.hariharan_at_gmail.com)
Date: 10/31/04


Date: 31 Oct 2004 09:26:54 -0800

Hello all.

My question comes in two parts:

[1] This is more a request than a question. Please post examples
that show abuse/misuse/poor usage of std::string's c_str() member
function. Please discuss usages that lead to undefined behaviour
(runtime) as opposed to those that lead to compilation errors.

E.g.,

const char * func()
{
    std::string s("Hello");
    return s.c_str();
}

You could also point to examples in literature (e.g., "Stroustrup in
TCPL discussing temporaries", etc.) or on the web (e.g.,
http://groups.google.com/groups?selm=3E54CD7D.1020604%40crf.canon.fr).

TIA.

[2] Say I work in a non-trivial project with many, many functions
that accept a char * as an argument, a number of those possibly
modifying it. I have to call many of those, and I have a std::string
with me. One might do -

std::string s;
// ...
{
   size_t len = strlen(s.c_str());
   char* cs = new char[len+1];
   strcpy(cs, s.c_str());

   func(cs,len);

   s = cs;
   delete [] cs;
}

This becomes onerous if one has to do this for every function. What
is the easiest way to accomplish this?

Thank you for listening.

sincerely,
- Anand