Help debugging basic_string<char>

Jamie Kirkpatrick jkp@kirkconsulting.co.uk
Mon Jan 23 14:44:00 GMT 2006


On 23 Jan 2006, at 14:06, Neil Bird wrote:

> Around about 23/01/06 09:16, Jamie Kirkpatrick typed ...
>>> std::string getString();
>>> void f()
>>> {
>>>     const char* p = getString().c_str();
>>>     // use p
>>> }
>>>
>> Ok - this is what I meant.  So what im seeing is correct OK, thats  
>> good I guess!  Is there something in the c++ spec i can point  
>> people too to indicate that this is the case?  An out of interest  
>> - how come the destructor on string is not getting called so soon?
>
>   Nothing specific, it's more about understanding what's happening.  
> getString is returning a transient std::string which will only live  
> for the duration of the statement.  You're calling .c_str() on  
> this, and that's fine.  But at the end of the statement (after the  
> assignment) the string goes out of scope, its destructor is called  
> and the memory opinted to by the c_str() is invalid.
>
>   You have two alternatives;  if getString() is accessing a long  
> term store you can guarantee will be around, you can make it return  
> a reference, maybe even a const ref. (which would be better), so  
> you're not accessing the transient but the original.
>
>   Alternatively, keep a copy yourself:
>
> const std::string& getString();
> void f()
> {
>     const char* p = getString().c_str();
>     // use p
> }
>
> or
>
> std::string getString();
> void f()
> {
>     const std::string s = getString;
>     const char* p = s().c_str();
>     // use p
> }


Great - thats a nice concise explanation.

>
>
>>  Also, is it ok to assume that the following is valid?
>> int test( char * buffer );
>> main()
>> {
>>     int result = test( someFunctionReturningString().c_str 
>> () );            // buffer valid for duration of subsequent call?
>> }
>
>   Yes;  in this case the transient string is valid till after  
> 'test' returns.  The specs. probably got something to say about the  
> lifetime of objects created on the stack for function calls.

Good - I had hoped as much.....

>
>
>   Can't help with the rest as I've not done that sort of thing.

Shame - im getting an extremely difficult to track down memory error  
now - double free in the destructor for basic_string<> :/

anyone fancy a go!? :p

Thanks

Jamie



More information about the Libstdc++ mailing list