Warning in <TFile::Append>: Replacing existing TH1: qs_proj_0 (Potential memory leak)

Hi, I am trying to run a C++ code to plot and project a n-dimensional histogram, However I get several warnings of potential memory leak. Can you help me solve it.

I am attaching a part of the macro for your review:

Int_t xl =100; Int_t yl =100",“”, xl, yl);

TFile *FLM = new TFile(“fg.root”);

THnSparse LD = (THnSparse)FLM->Get(“o/s/qs”);
THnSparse ULD = (THnSparse)FLM->Get(“o/s/qd”);

vector<vector <TH1F*>> F1DL(50);
vector<vector <TH1F*>> F1DU(50);

const int sNch = 48;
const int kNch = 47;
const int nkT = 5;

Double_t ML[kNch]= {0,5,10,13,16,19};
Double_t MH[kNch]= {4,9,12,15,18,21};

Int_t FLB; Int_t FHB;

for (int im=0; im<=kNch; im++)

// set bin of Ntrk

 FLB  = ULD->GetAxis(2)->FindBin(ML[im]);

FHB = ULD->GetAxis(2)->FindBin(MH[im]);

LD->GetAxis(2)->SetRange(FLB, FHB);

ULD->GetAxis(2)->SetRange(FLB, FHB);

cout<<  im <<  " " <<  FLB <<  " " <<  FHB << endl;

for (int ikT=1; ikT<=nkT; ikT++){

 Double_t FLV; Double_t FHV;
  if(ikT==1){ FLV = 0; FHV = 20;}
  if(ikT==2){ FLV = (ikT)*0.10+0.0009; FHV = (ikT+1)*0.10-0.0009;}
  if(ikT==3){ FLV = (ikT)*0.10+0.0009; FHV = (ikT+1)*0.10-0.0009;}
  if(ikT==4){ FLV = (ikT)*0.10+0.0009; FHV = (ikT+1)*0.10-0.0009;}
  if(ikT==5){ FLV = (ikT)*0.10+0.0009; FHV = (ikT+2)*0.10-0.0009;}
  Int_t FVL  = ULD->GetAxis(1)->FindBin(FLV);
 Int_t FVH = ULD->GetAxis(1)->FindBin(FHV);

  LD->GetAxis(1)->SetRange(FVL, FVH);
 ULD->GetAxis(1)->SetRange(FVL, FVH);
   if (MH[im] < 12){
   F1DL[im].push_back((TH1F*)LD->Projection(0, Form("ftum_%d_%d",ikT,im)));


Hi there,
welcome to this forum! It seems like your code is not shown properly here (Probably includes “>” and “*”). Maybe you can edit it so that it is better to read. Thus I can try to run your code.
Still, what I suspect is happening, is that your Histogram has the same name all the time, so when appending it to the TFile, the old one is deleted. Yet, I am not very experienced and therefor this could easily be wrong.
I have never worked with multiple histograms, but the THnSparce Documentation for Projection has no “Name” option (as far as I have seen). A rather forced way would be this:

TH1F* Histogram = (TH1F*) LD->Projection(0);


Hi Emil,
Thank you very much for your suggestion.
I implemented your piece and it worked fine.

1 Like

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