Graphing with Root Using Pointers

I am using ROOT with macros, and I creating a histogram, like this:

    TCanvas *c1 = new TCanvas("sinh","c1");
   TH1D* example = new TH1D("example","example histogram", 10,-3,3);
   example->FillRandom("gaus",100000);
   example->Draw();
    c1->Draw();

but when i run the program I get the following message:

Warning in TCanvas::Constructor: Deleting canvas with same name: sinh
Warning in TROOT::Append: Replacing existing TH1: example (Potential memory leak).

so I added at the end of the code (delete c1;
delete example;) but I still got the same error and I erased my graph before i could see it.


ROOT Version: Not Provided
Platform: Not Provided
Compiler: Not Provided


make a named macro:

file ip25.C:

void ip25(){
   auto c1 = new TCanvas("sinh","c1");
   TH1D* example = new TH1D("example","example histogram", 10,-3,3);
   example->FillRandom("gaus",100000);
   example->Draw();
   c1->Draw();
}

just, out of curiosity, is there a particular reason why you’d prefer auto c1 rather than TCanvas *C1?

just more modern C++ :slight_smile:

1 Like

btw you can also do:

   auto example = new TH1D("example","example histogram", 10,-3,3);

another question, how can I free those address from memory without using delete?

void ip25() {
   // Create the "sinh"canvas only if it does not exist
   TCanvas *c1 = (TCanvas*) gROOT->GetListOfCanvases()->FindObject("sinh");
   if (!c1) c1 = new TCanvas("sinh","c1");

   // create the histgram only if it does not exist
   TH1D *example = (TH1D *)gROOT->FindObject("example");
   if (!example) example = new TH1D("example","example histogram", 10,-3,3);

   example->FillRandom("gaus",100000);
   example->Draw();
}

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