Vector of TBranches Access Segfault


_ROOT Version:_5
Platform: Scientific Linux 6.10
Compiler: G++ 4.4.7


Hi, everyone, I am getting segfaults when I try to access elements of a vector of TBranch*. Here is a minimal working version of the code. I read TTree objects out of a TFile, and then store all the TBranches in a vector. Further down the line I try to access each of the TBranch elements of a vector and as soon as I try that, I get a segfault.

#include <iostream>
#include <TFile.h>
#include <TTree.h>
#include <TBranch.h>
#include <TKey.h>

using namespace std;

int main(){

  int i = 0;
  vector<TBranch*> Detectors;
  
  TFile* data = TFile::Open("Data.root");
  TKey *key = 0;
  TTree* event = 0;
  TBranch* detector = 0;
  TObjArray* branch_list = 0; 
  
  if(data->IsOpen()){
  	
  	TIter next_event(data->GetListOfKeys()); 
    
		while((key = (TKey*)next_event())){
		
		  if(strcmp(key->GetClassName(), "TTree")){
		  
		    continue;
		  }
		  
		  event = (TTree*)data->Get(key->GetName()); 
		  branch_list = event->GetListOfBranches();
		  
		  for(i = 0; i < branch_list->GetEntries(); i++){
		  
		    detector = (TBranch*)branch_list->At(i); 
		    Detectors.push_back(detector);
		  }
		  
		  delete event;
		}
  }
  
  else{cout << "ERROR: File failed to open." << endl;}
  
  data->Close();
  
  //Segfaults occur in this loop!
  for(i = 0; i < Detectors.size(); i++){
  
    Detectors[i]->Print();
  }
  
  Detectors.clear();

  return 0;
}

The data->Close(); automatically deletes the tree (and all its branches).

Thank you for the information. That makes a lot of sense. That said, I have moved the Close() statement so that it’s after the Print() for loop. The segfault, however, still occurs.

Well, delete event; deleted all its branches as well.

1 Like

That fixed it, thanks!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.