# Behavior of TFile::Open() in a loop

**URL:** <https://root-forum.cern.ch/t/behavior-of-tfile-open-in-a-loop/57390>\
**Category:** Newbie\
**Tags:** root\
**Created:** [December 4, 2023, 9:18pm UTC](https://root-forum.cern.ch/t/behavior-of-tfile-open-in-a-loop/57390 "2023-12-04T21:18:08Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![jocl](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/jocl/32/35197_2.png) [@jocl](https://root-forum.cern.ch/u/jocl)\
**Post date:** [December 4, 2023, 9:18pm UTC](https://root-forum.cern.ch/t/behavior-of-tfile-open-in-a-loop/57390/1 "2023-12-04T21:18:08Z")

</div>

* * *

_ROOT Version:_ 6.26/06  
_Platform:_ Scientific Linux 7.3 (Nitrogen)  
_Compiler:_ None (macro)

* * *

Hi ROOT forum,

I am seeing some behavior that I don’t understand when I open TFiles within a loop. This may be an issue with my understanding of C++, but I am not sure.

My code (broadly) looks like this:

```auto
for(int i=0; i<nfiles; ++i)
  {
    TFile* file = TFile::Open(("myfile_"+to_string(i)+".root").c_str());
    TTree* tree = file->Get<TTree>("ttree");
    //some operations on file/tree
  }

```

The memory usage of my program climbs in increments of the size of my\_file\_i.root, which looks to me like a memory leak.

However, when I do this:

```auto
for(int i=0; i<nfiles; ++i)
  {
    TFile* file = TFile::Open(("myfile_"+to_string(i)+".root").c_str());
    TTree* tree = file->Get<TTree>("ttree");
    //some operations on file/tree
    delete file;
  }

```

The memory leak goes away. So obviously file is never deleted, and just hangs around in memory, and can’t be freed (that’s a memory leak alright).

Why does this happen? I would think that an object instantiated inside a loop dies at the end of the loop. Not so?

Thanks!

---

<div class="post-metadata">

**Author:** ![pcanal](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/pcanal/32/12439_2.png) [@pcanal](https://root-forum.cern.ch/u/pcanal)\
**Post date:** [December 4, 2023, 9:44pm UTC](https://root-forum.cern.ch/t/behavior-of-tfile-open-in-a-loop/57390/2 "2023-12-04T21:44:39Z")

</div>

`TFile::Open` acts (for the purpose of this discussion) indirectly as calling `operator new`, so the code above is similar to:

```auto
for(...) {
   someclass *obj = new someclass;
}

```

where the object is allocated but never deleted (i.e. memory leaks).

Cheers,  
Philippe.

‘Technically’ with `TFile::Open` this is not a leak but ‘hoarding’ as the file objects will be deleted … at the end of the process.
