Search code examples
c++root-framework

Getting error Filled mass arrayAborted (core dumped) in loop that fills histogram


I am trying to run a for loop that fills a histogram array. Whenever I run this code I keep getting the same error, stating:

"Error in `./Analysis.exe': free():" *Some memory locations* 
"Filled mass arrayAborted (core dumped)"

I'm new to c++ so there is likely some memory thing that I am not considering here.

I Have tried analyzing where the loop fails by changing the "Max" variable such that the loop only continues up to a predefined point. It turns out that the loop always fails on the last iteration of the loop. It seems like the loop is going over the predefined memory, which is why I allocated (I think) enough memory to the variable mm before the start of the loop.

'''
int main(){

  // Initializing the pointers' types
  TFile *f;
  TDirectoryFile *dir;
  TTree *tr;
  TCanvas *BM_canvas;

  // Initializing the B mass variable
  Double_t        B_M;

  // Opening the file
  f = new TFile("*Name of root file*");

  // Extracting the directory from the file
  dir = (TDirectoryFile*)f->Get("*Name of TDirectory file*");

  // Extracting the tree from the directory
  tr = (TTree*)dir->Get("*Name of tree*");

  // Setting the branch address to a pointer with the same name
  tr->SetBranchAddress("B_M", &B_M);

  // Getting the number of entries and printing
  int nentries=tr->GetEntries();
  cout<<nentries<<endl;

  // Defining a histogram for the mass
  TH1F *Mass = new TH1F("Mass","",10000,0,100000);

  int max = 7915;
  double *mm;
  mm = new double[max];


  for (int i=0; i<max; i++){

      tr->GetEntry(i);

      *mm = B_M;
      if (mm != 0){
    Mass->Fill(*mm);
      }

 }

  cout << "Filled mass array";

  return 0;
}
'''

I expect the result to be a filled Mass array with the entries taken from the leaves "B_M' in the root file.

I have tried leaving out the mm variable altogether since this could have caused the problem, however the same error persists. Even when I leave out the loop I get an error saying "* Break * segmentation violation"


Solution

  • The problem is solved. I am not sure why but "TH1D *Mass = new TH1D(....)" had to be initialized before opening the TFile. My guess for as to what the solution here is is that I do not have access to write to the TFile and that defining the TH1D after the TFile made it such that the TH1D was written to the TFile.