Problem in loading a Macro more than on time

_ROOT Version: 6.20/02
Platform: Ubuntu 20 on WSL2
Compiler: Not Provided


Hi all,

I am having some issue with a simple Macro i wrote. In principle it should be able to create an histogram, fill it randomly with a gaussian distribution, then fit it and save it to a file.
When I run the macro the first time (using .L ) I don’t have any problems, and it works properly,
but when I try to run it again I end up with several memory errors.
After some try i discovered that the problem occurs when I set both Fit and Write.

Here is the code:

 auto *file = new TFile("file.root","RECREATE");   
  //std::unique_ptr<TFile> file(TFile::Open("file.root","RECREATE"));
  auto *h1= new TH1D("h1","Random Gaus",1000,-10,10);
  auto *c1=new TCanvas();
  TRandom3 rnd;
  double value=0;
  for(int i=0;i<1000;i++){
  value=rnd.Gaus(0,1);  
  h1->Fill(value);
  }
   auto *g= new TF1("g","gaus",-1,1);
   g->SetParameter(1,1);

  h1->Fit("g"); //when I put both Write and Fit have the memory problem
  h1->Write(); 
  file->Close();

 //delete h1;
 delete g;
 delete file;
 delete c1;


return 0;
} ``` 

The error message is quite long but it begins with

*** Break *** segmentation violation
Generating stack trace…
and it consists in line such as
0x0000563efa1d9baf in from.

Thanks to anybody will read this.

Hi @GIULIO_89,

welcome to the root forum. I tried running your code and it works well for me, I don’t get any memory errors (I loaded it and tried running a few times). but maybe simplifying your code a bit could help, maybe try something like:

void TestFit_Write()

{    
    TH1F h("my_histogram","histogram",1000,-10,10);

    // Let's fill it randomly
    h.FillRandom("gaus");

    auto *g= new TF1("g","gaus",-1,1);
    g->SetParameter(1,1);

    h.Fit("g");

    // Let's open a TFile
    TFile file("file.root","RECREATE");

    // Write the histogram in the file
    h.Write();

    // Close the file
    file.Close();

}

Cheers,
Marta