[PLUG] C++ pointer freeing problem

Carlos Konstanski ckonstanski at pippiandcarlos.com
Mon Feb 15 05:56:30 UTC 2010


On Sun, 14 Feb 2010, Tony Rick wrote:

> Date: Sun, 14 Feb 2010 21:39:48 -0800
> From: Tony Rick <tonyr42 at gmail.com>
> Reply-To: "General Linux/UNIX discussion and help;	civil and on-topic"
>     <plug at lists.pdxlinux.org>
> To: "General Linux/UNIX discussion and help,	civil and on-topic"
>     <plug at lists.pdxlinux.org>
> Subject: Re: [PLUG] C++ pointer freeing problem
> 
> On Sun, Feb 14, 2010 at 8:34 PM, Erik Lane <eriklane at gmail.com> wrote:
>
>> I believe that that might not work as you expect. you don't own the
>> position of the return pointer from c_str(), so you can't guarantee
>> when it will still be around. (Well C++ gurus possibly could, but I
>> don't know.)
>>
>> Therefore I would make your own variable pointer. And new[] it with
>> the length of the rawInput + 1. Then use strcpy() to copy over the
>> char array from one to the other.
>>
>> IE:
>>    char * charSequence = new char[rawInput.length()+1];
>>    strcpy(charSequence, rawInput.c_str());
>>
>> Then of course you need to use delete[] when you are done with it.
>>
>> But I haven't had a chance to check it in Visual C++ yet. Hopefully
>> I'll get a look at it in a little bit after kids are asleep. If not
>> tonight it won't be until tomorrow evening that I'll get a chance.
>>
>> Erik
>
>
> Your point about guarantees on the existence of the result of the call to *
> c_str()* is well taken.  The features of string member function
> *c_str()*are explained here:
> http://www.cplusplus.com/reference/string/string/c_str/ .  One of the things
> it says is that the existence of that result is only guaranteed until the
> next call to a non-constant member function.  I'm thinking that this is the
> crux of the matter, and that implementations differ between the VC++ and
> g++.  The fact that my suggested modification seems to have worked for
> Carlos, in my opinion, does not imply the 'correctness' of the solution.
> Working within the restrictions of the defined behavior, however, would seem
> to be the way to go.
>
> - tony

The way I read it, as long as I don't call any further methods on
rawInput after the *char assignment, I am OK. I violate this rule by
calling rawInput.size(). So I will capture the size of the string
before the *char assignment, and all will be golden.

Carlos



More information about the PLUG mailing list