Segmentation fault in GetBinContent

Hello Rooters,
I was trying to draw 1D histograms for each 2D bins. For that I used 2D array and defined them as follows.
I am getting segmentation error in the following code part.

//histogram definition

TH1F *h_pimMX2array_3fold_bgnd[i_theta_bins][n_p];
    char histName_3fold_bgnd[64];
    for (int ith=0; ith<i_theta_bins; ith++) {
        for (int ippim=0; ippim<n_p; ippim++) {
            sprintf(histName_3fold_bgnd,"h_pimMX23foldbgndarray_p%03d_th%03d",ippim,ith);
            h_pimMX2array_3fold_bgnd[ith][ippim] = new TH1F(histName,"3fold and 4fold Missing pimMassSq",300,-0.5,0.5);
        }
    }


TCanvas *canEfficiency = new TCanvas("canEfficiency","",12000,6000);
    canEfficiency->Divide(4,3);
for (int ith=0; ith<3; ith++) {
        for (int ippim=0; ippim<4; ippim++){
            double n3bgnd[ith][ippim];
             n3bgnd[ith][ippim] =h_pimMX2array_3fold_bgnd[ith][ippim]->GetEntries();
            // remove overflows and underflows (should be 0)
            n3bgnd[ith][ippim] += -h_pimMX2array_3fold_bgnd[ith][ippim]->GetBinContent(0);
            n3bgnd[ith][ippim] += -h_pimMX2array_3fold_bgnd[ith][ippim]->GetBinContent( h_pimMX2array_3fold_bgnd[ith][ippim]->GetNcells()-1); //fault is somewhere in this line???


}
}

the break happen in the following line.

n3bgnd[ith][ippim] += -h_pimMX2array_3fold_bgnd[ith][ippim]->GetBinContent( h_pimMX2array_3fold_bgnd[ith][ippim]->GetNcells()-1);

So I tried this with

n3bgnd[ith][ippim] += -h_pimMX2array_3fold_bgnd[ith][ippim]->GetBinContent( h_pimMX2array_3fold_bgnd[ith][ippim]->GetNcells()-1,h_pimMX2array_3fold_bgnd[ith][ippim]->GetNcells()-1 );

This also gave me the segmentation fault.
Any help would be greatly appreciated.

Thanks
Dilini

Is β€œi_theta_bins >= 3” and β€œn_p >= 4”?

Instead of (inside of loops):
double n3bgnd[ith][ippim];
use (outside of loops!):
double n3bgnd[i_theta_bins][n_p];

BTW. Instead of:
h_pimMX2array_3fold_bgnd[ith][ippim]->GetNcells()-1
use (a more β€œclear”):
h_pimMX2array_3fold_bgnd[ith][ippim]->GetNbinsX()+1

1 Like

Also, to make the code clearer and easier to maintain, prefer

a -= b;

to

a += -b;

(but this is not in any way the source of your segmentation fault of course)

Thank you Wile and yus.It worked
-Dil

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