Hugh memory leak issue

Hi Rooters,

I am having huge memory leak while writing the classes in a root file. Classes are like this:
“Track” class hold one track, “TimeStep” class hold one time interval, which can have thousands of “Track” objects held in a std::vector, and “Event” class hold one event, which can have hundreds of “TimeStep” objects held in a std::vector.

The macro reads text file and write to a root file. It leaks/uses a lot of memory while filling tracks to “TimeStep”. Even after writing one event to the root file, it does not free the memory.

// write one event
int writeOneEvent(ifstream& in, TFile *file, Event *event, TTree *tree)
        double ro, rx;
        TimeStep *timeStep = new TimeStep();
        timeStep->Init();  // it clear the vector holding the tracks	
   	// // // HUGE MEMORY LEAK in this loop // // //
        for(int i=0; i<nTracks; i++) {
                if(!in.eof()) {
                        in >> ro >> rx;
                        // this push the Track object into the std::vector in TimeStep class.
                        timeStep->AddTrack(ro, rx);
         // this push the TimeStep object into the std::vector in Event class.

        // some other codes
        if(int(ro) == totalSteps) newEvent = true;

        if(newEvent || in.eof()) {
                tree->Fill();           // fill the tree after each event
                // it delete the pointer to the vector which hold tracks.
                // it delete the pointer to the vector which hold timestep objects.
                return 1;
        return 0;

It works fine if I write only one root file with < 10 events. Any suggestion? I guess this the issue is related to ROOT rather than C++. I first tried TClonesArray but it did not work.



I do not see an obvious problem with the code you posted. However, the internal workings of your classes aren’t entirely clear to me. Did you verify yet that there is no leak if you remove the ROOT-related parts in the code?

What makes me a little bit wonder is this part of your code:

                 // it delete the pointer to the vector which hold timestep objects.

If the comment is correct, you have a memory leak here. From

TimeStep *timeStep = new TimeStep();

I deduce that you do not have a std::vector, but a std::vector<TimeStep*>. On clearing the vector, you only remove the pointers to the TimeSteps from memory, but not the TimeSteps themselves.