Get Segfault when setting branch address in different functions

Dear experts

I passed a TTree to another function and set branch addresses there for 3 variables a b c, and then I set the branch address in the main function again for 2 variables a b, then set fault occurs when I try to GetEntry(). Why?

int main(){
//omit
int[3] a;
int[3] b;

TTree* t = (TTree*)f->Get("t");

DoIt(t);

t->SetBranchAddress("a", &a);
t->SetBranchAddress("b", &b);

t->GetEntry(0); //Segfault here
//omit
}

void DoIt(TTree* t){
int[3] a;
int[3] b;
int[3] c;
t->SetBranchAddress("a", &a);
t->SetBranchAddress("b", &b);
t->SetBranchAddress("c", &c);
//omit
}

Hi,

The variables the addresses of which you are using are allocated on the stack of the function you mention. When returning these addresses become invalid.

Best,
Danilo

Thank you, but I’m not using them in the main function, and I reset the address for a and b, not for c because I won’t use it, but still got segfault.

Reset the branch addresses just before leaving DoIt:

//...
t->SetBranchAddress("a", &a);
t->SetBranchAddress("b", &b);
t->SetBranchAddress("c", &c);
//...
t->ResetBranchAddresses();
}

Hi,

Correct. However, their address is still saved in the TTree branches. A way to avoid that, is indeed what @dastudillo proposed.

Cheers,
D

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