# How to properly delete TTree\* and TGraph\* and renew them

**URL:** <https://root-forum.cern.ch/t/how-to-properly-delete-ttree-and-tgraph-and-renew-them/55351>\
**Category:** Newbie\
**Tags:** root\
**Created:** [June 19, 2023, 1:50pm UTC](https://root-forum.cern.ch/t/how-to-properly-delete-ttree-and-tgraph-and-renew-them/55351 "2023-06-19T13:50:49Z")\
**Posts on this page:** 10\
**Page:** 1

<div class="post-metadata">

**Author:** ![Crisps](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/crisps/32/39101_2.png) [@Crisps](https://root-forum.cern.ch/u/Crisps)\
**Post date:** [June 19, 2023, 1:50pm UTC](https://root-forum.cern.ch/t/how-to-properly-delete-ttree-and-tgraph-and-renew-them/55351/1 "2023-06-19T13:50:49Z")

</div>

Dear Experts

I want to declare a pointer of `TGraph`, `TFile`, `Three` and `TH1D` and use `new` method for them inside a for loop, at the end of one loop I `delete` them so that I can reuse them at the next loop. Here is what I wrote:

```auto
int main(){
    TGraph* g;
    TFile* f;
    TH1D* h;
    
    for(some loop conditions){
         g = new TGraph();
         h = new TH1D();
         f = new TFile("some.root");
         TTree* t = (TTree*)f->Get("tree");
         
          //do something here

         delete g;
         delete f;
         delete h;
         delete t;
    }

    return 0;
}

```

But I got error when finished the very first loop:

```auto
MakeGainCurve(90527,0x100f88580) malloc: *** error for object 0x121f82580: pointer being freed was not allocated
MakeGainCurve(90527,0x100f88580) malloc: *** set a breakpoint in malloc_error_break to debug

```

What I did wrong?

---

<div class="post-metadata">

**Author:** ![vpadulan](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/vpadulan/32/25315_2.png) [@vpadulan](https://root-forum.cern.ch/u/vpadulan)\
**Post date:** [June 19, 2023, 2:57pm UTC](https://root-forum.cern.ch/t/how-to-properly-delete-ttree-and-tgraph-and-renew-them/55351/2 "2023-06-19T14:57:21Z")

</div>

Hi @Crisps ,

I cannot stress this enough, please refrain absolutely from implementing your code with the pattern you show. No `new` or `delete` statements should be visible in user code in modern C++ applications. Try to reframe your application so that ideally you don’t need raw pointers, or if you strictly need them then the lifetime and ownership of objects should be controlled and understandable. Let me give you an example

```cpp
TTree *myTree;
for (condition){
    std::unique_ptr<TFile> f{TFile::Open("myfile.root")};
    myTree = f->Get<TTree>("myTree");
    // use myTree in the loop
   // CRUCIAL: test the raw pointer
   if(myTree){
        // use it after the check, otherwise you could have a nullptr
   }
   // Anything that is created manually inside the loop, shouldn't be created with `new`
   TGraph myGraph{};
    TH1D myTH1D{};
}

```

In the example above, it is clear that `TTree *` is just a view on the tree owned by the `TFile`. Since it is wrapped by a `unique_ptr` the management will be done automatically and both the tree and file will be deleted appropriately at the end of the scope.

---

<div class="post-metadata">

**Author:** ![Crisps](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/crisps/32/39101_2.png) [@Crisps](https://root-forum.cern.ch/u/Crisps)\
**Post date:** [June 20, 2023, 5:23am UTC](https://root-forum.cern.ch/t/how-to-properly-delete-ttree-and-tgraph-and-renew-them/55351/3 "2023-06-20T05:23:13Z")

</div>

Thank you for the explanation! Just curious about the example you showed, I can use a raw pointer of `TTree` because the memory it pointing is owned by the `TFile` and will be released after every loop?  
If I want to use a `unique_ptr` for `TTree` inside the for loop just the same as `TFile`, how should I write? Because `Get()` function will return a raw pointer so I don’t know how to cast it to a `unique_ptr`.

---

<div class="post-metadata">

**Author:** ![vpadulan](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/vpadulan/32/25315_2.png) [@vpadulan](https://root-forum.cern.ch/u/vpadulan)\
**Post date:** [June 20, 2023, 2:55pm UTC](https://root-forum.cern.ch/t/how-to-properly-delete-ttree-and-tgraph-and-renew-them/55351/4 "2023-06-20T14:55:00Z")

</div>

Yes, you can surely use `unique_ptr` everywhere (and I highly suggest you to do so!)

```cpp
for (...){
   std::unique_ptr<TFile> f{TFile::Open("myfile.root")};
   // Pointers should be always checked to avoid use of nullptr
   if (!f){
      // The file is not properly opened, do something about it
      throw std::runtime_error();
   }
   std::unique_ptr<TTree> myTree{f->Get<TTree>("myTree")};
   if (!myTree){
      // The tree was not properly extracted from the file, do something about it
      throw std::runtime_error();
   }
   // Anything that is created manually inside the loop, shouldn't be created with `new`
   TGraph myGraph{};
   TH1D myTH1D{};
}

```

In general, whenever a function returns a `T *` which ownership is given to you (the caller), just wrap it with a `unique_ptr` as shown above. This is usually the case for legacy functions that were written before C++11.

Cheers,  
Vincenzo

---

<div class="post-metadata">

**Author:** ![Crisps](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/crisps/32/39101_2.png) [@Crisps](https://root-forum.cern.ch/u/Crisps)\
**Post date:** [June 21, 2023, 2:14am UTC](https://root-forum.cern.ch/t/how-to-properly-delete-ttree-and-tgraph-and-renew-them/55351/5 "2023-06-21T02:14:19Z")

</div>

Thank you @vpadulan !  
I understood how to use `unique_ptr` and will try to use it 🙂  
Can I just ask one question for curiosity, if I use the old school style of raw pointers for objects (just like my original question), what is the correct way to use them? I mean I thought that was the correct way:

create new pointers outside the loop and `new` at the begin of every loops then `delete` them at the end of every loops so that I can `new` them again at the exit loop.

Sorry because this may not related to ROOT but to c++ itself…

---

<div class="post-metadata">

**Author:** ![yus](https://root-forum.cern.ch/letter_avatar_proxy/v4/letter/y/9fc348/32.png) [@yus](https://root-forum.cern.ch/u/yus)\
**Post date:** [June 21, 2023, 8:56am UTC](https://root-forum.cern.ch/t/how-to-properly-delete-ttree-and-tgraph-and-renew-them/55351/6 "2023-06-21T08:56:46Z")

</div>

Hi,

I think the issue here is that you do

> [@Crisps](#):
>
> ```auto
> delete t;
> 
> ```

without the corresponding `new`.

---

<div class="post-metadata">

**Author:** ![vpadulan](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/vpadulan/32/25315_2.png) [@vpadulan](https://root-forum.cern.ch/u/vpadulan)\
**Post date:** [June 21, 2023, 9:01am UTC](https://root-forum.cern.ch/t/how-to-properly-delete-ttree-and-tgraph-and-renew-them/55351/7 "2023-06-21T09:01:09Z")

</div>

What @yus suggests is true, in fact you are not creating your `TTree *t` with a `new`. Instead you are getting it as a result from `TFile::Get`. The `TFile` is the owner of the `TTree`, so if you delete it manually like you are doing, then the `TFile` will delete it again when going out of scope, and that will trigger a double delete.

---

<div class="post-metadata">

**Author:** ![Crisps](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/crisps/32/39101_2.png) [@Crisps](https://root-forum.cern.ch/u/Crisps)\
**Post date:** [November 27, 2024, 4:19pm UTC](https://root-forum.cern.ch/t/how-to-properly-delete-ttree-and-tgraph-and-renew-them/55351/8 "2024-11-27T16:19:54Z")

</div>

Sorry that I reply to this old question! But I’m a little confused about this:

```auto
for(...){
   std::unique_ptr<TFile> f{TFile::Open("myfile.root")};
   // Pointers should be always checked to avoid use of nullptr
   if (!f){
      // The file is not properly opened, do something about it
      throw std::runtime_error();
   }
   std::unique_ptr<TTree> myTree{f->Get<TTree>("myTree")};
   if (!myTree){
      // The tree was not properly extracted from the file, do something about it
      throw std::runtime_error();
   }

  //Do something
  
   f->Close();
}

```

The code you showed before, I just got the question that will not the `TTree` be double deleted when the `std::unique_ptr` reach the end of its lifetime?

---

<div class="post-metadata">

**Author:** ![vpadulan](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/vpadulan/32/25315_2.png) [@vpadulan](https://root-forum.cern.ch/u/vpadulan)\
**Post date:** [November 29, 2024, 11:51am UTC](https://root-forum.cern.ch/t/how-to-properly-delete-ttree-and-tgraph-and-renew-them/55351/9 "2024-11-29T11:51:02Z")

</div>

Dear @Crisps ,

When the TTree will be destroyed it will deregister itself from the file, so there will be no double-delete. Also, the `f->Close()` in your example is redundant, the TFile destructor will already do the equivalent, yet another reason to use a proper data structure such as `std::unique_ptr` in this case.

Cheers,  
Vincenzo

---

<div class="post-metadata">

**Author:** ![Crisps](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/crisps/32/39101_2.png) [@Crisps](https://root-forum.cern.ch/u/Crisps)\
**Post date:** [December 5, 2024, 1:34am UTC](https://root-forum.cern.ch/t/how-to-properly-delete-ttree-and-tgraph-and-renew-them/55351/10 "2024-12-05T01:34:28Z")

</div>

Thank you for your answer, so that means after `TFile` is closed `TTree` is deregistered and the `unique_ptr` of `TTree` won’t trigger a deletion?

```auto
for(...){
   std::unique_ptr<TFile> f{TFile::Open("myfile.root")};
   // Pointers should be always checked to avoid use of nullptr
   if (!f){
      // The file is not properly opened, do something about it
      throw std::runtime_error();
   }
   std::unique_ptr<TTree> myTree{f->Get<TTree>("myTree")};
   if (!myTree){
      // The tree was not properly extracted from the file, do something about it
      throw std::runtime_error();
   }

  //Do something
  
  //TFile destroyed here by destructor of unique_ptr of TFile
  //TTree destroyed?? here by destructor of unique_ptr of TTree?
}
```
