Home | News | Documentation | Download

<TROOT::Append>: Replacing existing TH1: h (Potential memory leak)

Hi everyone.
I have an warning when I run my code. This warning was discussed more times in the past. I have read some posts related this topic but it can not help me to pass this problem.
My code has only a histogram. I do not create a different histogram with a same name but the warning still appear. How can I deal with the problem?

#include <TF1.h>
#include <TH1.h>
using namespace std;

TH1D *h = new TH1D("h", "his", 10, 0, 10);

double myfunc(double x);

void main()
{
    for (int i = 1; i <= h->GetNbinsX(); i++)
    {
        h->SetBinContent(i, i);
    }
    TF1 *f = new TF1("f", "myfunc(x)", 0, 10);
    f->Draw();
}
double myfunc(double x)
{
    double q = 0;
    for (int i = 0; i < 10; i++)
    {
        double g = h->GetBinContent(i+1);
        q = q + g*x;
    }
    return q;  
}

Warning in TROOT::Append: Replacing existing TH1: h (Potential memory leak).

Hi again,

I can’t reproduce your warning in ROOT 6.14/04. This is what I get, and there are no warnings/errors of any kind:

Could you maybe explain how you run your code? And what is your ROOT version/platform?

Hi.
This warning does not appear in the first time you run the code. But it appear in the next time you run the code (your IDE still opened). I am using Root 5.34.36 on Win 10, I also tried running on Ubuntu with root 6.18 anh there is a same warning.
Could you please try again?

Okay, I don’t use any IDEs (only CLI), so I guess I need to know how to reproduce it via the command-line interface. But maybe someone else has other ideas…

When I run code from macro ROOT, this problem also appeared in the second time. Here is photo.

Ah, of course. You have
TH1D *h = new TH1D("h", "his", 10, 0, 10);
, and running your macro twice in the same ROOT session is the same as running the following macro just once:

void example()
{
        TH1D *h = new TH1D("h", "his", 10, 0, 10);
        TH1D *h1 = new TH1D("h", "his", 10, 0, 10);
}

Hi.
I do not think so. As you said, I also have a object TF1 and in the second time I think it has to appear too (but it does not appear). I saw that this warning happens only with TH object.

This probably has to do with differences in object ownership between TH1 objects and others, TF1 in your case. Let’s wait for experts to chime in.

1 Like

@couet Could you please help me?

@yus is right. If you don’t need ROOT’s object lifetime management, call TH1::AddDirectory(false) before creating the first histogram, and you’ll get “regular C++ behavior”.