Subject: Re: Memory leaks
From: Joaquín Cuenca Abela (cuenca@pacaterie.u-psud.fr)
Date: Wed Jun 20 2001 - 05:54:41 CDT
On 20 Jun 2001 14:17:37 +1000, Martin Sevior wrote:
>
>
>
> On Tue, 19 Jun 2001, Dom Lachowicz wrote:
>
> > heap). So it's not like we're forgetting to call delete on them... or are we?
> > I'm thinking that the destructor should get implicitly called here: Expert
> > advice is sought after...
> >
> > void foo() {
> > UT_String bar = "hiya";
> > doSomething(bar);
> > // destructor implicity gets called as we leave scope
> > }
> >
>
> I can say that I've experimentally determined that pointers pointing to
> bar.c_str() inside foo , point to garbage outside foo. I had to move some
> UT_String 's to member variables because of this.
if you want to know the "theory" that explains that:
UT_String bar = "hiya"; // btw, please, use UT_String bar("hiya");
creates a variable named bar, and thus the constructor of UT_String is
called (in this particular example, the copy constructor of UT_String is
called, UT_String::UT_String(const UT_String&) )
when the variable goes out of scope, the destructor of bar will be
called (which will free any memory allocated by the constructor).
So, the scenario:
==================
1: char* tmp = 0;
2: {
3: UT_String bar("hiya");
4: tmp = bar.c_str();
5: }
6: printf("%s\n", tmp);
==================
has undefined results.
in the line 4, the pointer returned by c_str() points to a valid region
of memory (say 0x1000):
tmp -> 0x1000
and this region of memory you should have that:
+---+---+---+---+
| h | i | y | a |
+---+---+---+---+
in the line 5, bar goes out of scope, and thus the destructor of bar
will be called, that will free the memory allocated inside bar to store
the "hiya" string, so now, tmp still points to 0x1000 (nobody has
touched it), but the values stored at 0x1000 are indefined, you can have
whatever in this region of the memory after the destructor is called.
hope that it clarifies a bit all that stuff
> Cheers
>
> Martin
>
> Still an Experimental Scientist even while coding :-)
you will find that theory and experiments are much more heavily tied in
CS
than in physics (here there are not "disturbing" factors ;-)
P.S.: Please please please, change all ocurrences of
UT_String blah = "foo";
by
UT_String blah("foo");
in the code. The first form will create a unneeded temp object (with
the first
form we should strcpy & memcpy the string, with the later we only need
to strcpy
the string).
Cheers,
-- Joaquín Cuenca Abela cuenca@celium.net
This archive was generated by hypermail 2b25 : Wed Jun 20 2001 - 10:58:45 CDT