# Segfault after remove and delete TChain friend

**URL:** <https://root-forum.cern.ch/t/segfault-after-remove-and-delete-tchain-friend/14820>\
**Category:** ROOT\
**Created:** [August 24, 2012, 7:58pm UTC](https://root-forum.cern.ch/t/segfault-after-remove-and-delete-tchain-friend/14820 "2012-08-24T19:58:05Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![benloer](https://root-forum.cern.ch/letter_avatar_proxy/v4/letter/b/bb73d2/32.png) [@benloer](https://root-forum.cern.ch/u/benloer)\
**Post date:** [August 24, 2012, 7:58pm UTC](https://root-forum.cern.ch/t/segfault-after-remove-and-delete-tchain-friend/14820/1 "2012-08-24T19:58:05Z")

</div>

Hi all,

The following code block will cause a segfault (root 5.27 and gcc 4.1.2):

```auto
TChain* c1 = new TChain("data");
c1->Add("data*.root");
TChain* c2 = new TChain("cuts");
c2->Add("cuts*.root");

c1->AddFriend(c2);
c1->Draw("varincutstree");

c1->RemoveFriend(c2);
delete c2;

c1->SetBranchStatus("*",0);
```

It seems c1 still has some reference to the branches in c2 even after the friend is removed (and it _is_ removed from the ListOfFriends).

Until a bugfix happens, is there a reasonably convenient workaround? The use case is that my dataset is broken up into trees with interesting data and trees that are only really used to generate cuts. So I want to temporarily add the cut trees as friends just to generate a TEntryList, then get rid of them.

Thanks,  
~Ben

---

<div class="post-metadata">

**Author:** ![benloer](https://root-forum.cern.ch/letter_avatar_proxy/v4/letter/b/bb73d2/32.png) [@benloer](https://root-forum.cern.ch/u/benloer)\
**Post date:** [August 24, 2012, 9:23pm UTC](https://root-forum.cern.ch/t/segfault-after-remove-and-delete-tchain-friend/14820/2 "2012-08-24T21:23:33Z")

</div>

The following seems to get around the problem, by removing the friend from each of the chain’s subtrees, at least in my case:

```auto
Long64_t* offsets = parent->GetTreeOffset();
Long64_t entry = 0;
for(Int_t treenum=0; treenum < parent->GetNTrees(); ++treenum){
  entry += offsets[treenum];
  parent->LoadTree(entry);
  TTree* tree = parent->GetTree();
  tree->RemoveFriend(friend);
}
```

Not sure if it will work in all cases, but it would be nice to add this step to TChain::RemoveFriend.

~Ben

---

<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:** [September 19, 2012, 8:20pm UTC](https://root-forum.cern.ch/t/segfault-after-remove-and-delete-tchain-friend/14820/3 "2012-09-19T20:20:39Z")

</div>

Hi Ben,

This is corrected in the trunk (revision 46069) and in the v5-34 patch branch (v5.34/02 will be released at the end of the week and will include this fix).

Apriori to somewhat work around the problem you should just need:`parent->GetTree()->RemoveFriend( friendChain->GetTree() );`

Cheers,  
Philippe.
