Re: Who's responsible for deletion?

Rene Brun (Rene.Brun@cern.ch)
Fri, 11 Sep 1998 19:17:41 +0200


Patrick Schemitz wrote:
>
> Hi Rooters,
>
> I have a very basic question regarding memory management.
>
> In compiled code (using ROOT classes), using operator delete on
> instances of ROOT classes sometimes causes a segfault later on.
> (Of course I don't use the pointer after "delete", but nonetheless
> the program dumps core. And of course I don't use delete on
> automatic variables.)
>
> Omitting the deletion of dynamic instances of ROOT classes (TBRIK
> comes to my mind) seems _not_ to lead to a memory leak - how come?
>
> In some example programs in the tutorial you use constructs like
>
> mat = new TMaterial("mat1","HYDROGEN",1.01,1,.0708);
> mat = new TMaterial("mat2","DEUTERIUM",2.01,1,.162);
> mat = new TMaterial("mat3","HELIUM",4,2,.125);
> mat = new TMaterial("mat4","LITHIUM",6.94,3,.534);
>
> and so on. (From tutorials/na49.C.) "Normally" this is an absolute
> C++ no-no, but with ROOT it does not produce leaks.
>
> Who is actually responsible for memory management for the ROOT
> classes? Does the interpreter do memory management even when using
> a compiler? If it does, then how does it realize a pointer in the
> compiled C++ code goes out of scope so the pointee is to be
> deleted?

Patrick,
When you invoke the constructor for many Root objects, such as
histograms, Trees, materials, Nodes, these objects are automatically
added to some containers.
In the case of TMaterial, these objects are added to the list
of materials for the current geometry.
When you will delete the geometry object, all materials in this
geometry will be deleted.
Same behaviour for histograms automatically added to the list
of objects in the current directory.
If you write the object geometry onto a file, this object knows that
it must also write all its constituents, materials , nodes, etc.
There are absolutely no differences in behaviour between classes
created via the interpreter and classes created in the compiled code.
You can see the list of active classes/objects in memory with
gObjectTable->Print();

Rene Brun