Ellarco wrote:
Im sorry for asking a question that is surely in the archives somewhere, but
I have been unable to locate it.
Its about string memory management. I need to dynamically construct a
C-style string and was planning to go about it this way;
char* foo()
{
std::stringstream ss;
ss << ...
std::string s = ss.str();
char* c = s.c_str();
return c;
}
Bad idea.
AT the moment this function terminates, the object s is killed.
And since the object s is killed, so is the buffer it handed out
to you through c_str().
void main()
int main()
{
char* c = foo();
// work with c
delete(c);
wrong syntax. Must be delete [] c;
Please: always cut and paste code, don't write it directly in your
newsreader. Otherwise we are hunting bugs which simply are not there
in your real program.
Well. Did you allocate something? Did your documentation of c_str()
tell you to delete the buffer?
The answer is no in both cases. So, no, you don't have to delete
anything (but that will change in a short while :-)
As you have seen, you can't return what c_str() gives to you, since
the object itself goes out of scope and hence the buffer is deleted,
while doing so. From this it follows that you first have to create
a copy of the C-style string:
char* foo()
{
....
std::string s = ss.str();
char* c = new char [ s.size() + 1 ];
strcpy( c, s.c_str() );
return c;
}
Now foo hands out a dynamically allocated buffer which is filled with
a copy of what c_str() handed out.
And since this buffer was allocated with new[], you have to delete[]
it somewhere.
int main()
{
char* cc = foo();
....
delete [] c;
}
--
Karl Heinz Buchegger
kb******@gascad.at