Can't use pointer returned from Root Class Object

A Root class pointer defined in a function, but when it is returned out of the function, it can't be used any more

solution: Becuase the memory of the Root pointers are all managed by Root, when the function finished, the memory will be released by Root ( c++ don't do this) use pointer->SetDirectory(0) to let Root not to manage the momery of this pointer. or TH1::AddDirectory(kFALSE) to let Root not to manage memoty fo any pointers of TH1.

search memory problem


valgrind --tool=memcheck program

to find which lib produce the following error.

our example is 1. we copy a .h file from the A package to B package. 2. the .h define some class and objects 3. if load A and B lib, the object defined in .h are free-ed 2 times.


*** glibc detected *** /afs/cern.ch/sw/lcg/app/releases/ROOT/5.28.00g/x86_64-slc5-gcc43-opt/root/bin/root.exe: double free or corruption (!prev): 0x0000000006b91a40 ***
======= Backtrace: =========

Problem in using TTree::SetBranchAddress

When use TTree::SetBranchAddress to link variables to some of the branches (not all branches), some time, the link is not working as expected.

for example, SetBranchAddress("branch_a",&var_a) , but after tree->GetEntry(i), var_a may in fact get the value from branch_b, In this case branch_b is not linked to any variable.

To solve the prolbem:

to switch off all other not-used branches with SetBranchStatus( "branch_b", 0);

TChain read only the first file in the chain

When use TChain to chain several files and use "maked class" to read the events, it happened that only the first file is read once and once:
for( int i=0; i<tchain.GetEntries(); i++){

The correct should be 
for( int i=0; i<tchain.GetEntries(); i++){

ERRORs and reason/solutions

  • error message
Error: Symbol #include is not defined in current scope  (tmpfile):1:
Error: Symbol exception is not defined in current scope  (tmpfile):1:
Syntax Error: #include <exception> (tmpfile):1:
Error: Symbol G__exception is not defined in current scope  (tmpfile):1:
Error: type G__exception not defined FILE:(tmpfile) LINE:1
*** Interpreter error recovered ***

Reason and Solution: Memory leakage problem. When the leakage is getting big enough it produces this error. In the case pointer is defined and memory is allocated but didn't deleted after using.

  • "[ROOT] Load Error: Failed to load Dynamic link library"
 This usually happens when the compiler version used to build ROOT is not the
same as the compiler available in the path (i.e. bash> g++ -v).

  • Statement too long
reloading /atlas/czhu/myAnalysisCode/my_method/./method2_a.cxx  0
Limitation: Statement too long method2_a.cxx:197:
cint: Security mode 0x7:0x2 Error: Too many '}' method2_a.cxx:208: 

reason: has the following statement, just in the file method2_a.cxx (not inside any function)
for(int i=0;i<10;i++)pa_mceffi[i]=0.;
  • Unexpected EOF, need to use +P or -p option
reloading /atlas/czhu/myAnalysisCode/notes/notes_ele25/./T7CSCnote.cxx  0
Error: Unexpected EOF G__fignorestream():3 T7CSCnote.cxx:4159:
Advice: You may need to use +P or -p option

reason:      ""  or {}   don't  exist in pairs

  • error message as below:
root [1] CheckObjects(1000015)
open new data...$HOME/analysisResults/5205_12605_jcali_atlfast/ANA.ntuple.root
open the 3nd data...$HOME/analysisResults/5205_12605_jcali_fullsim_truthHardProc/ANA.ntuple.root

 *** Break *** segmentation violation
 Generating stack trace...
In happens, when program runs switch{case break; .....}. A very long double vector is defined in one of the (case break), which make all the (case, break) after the definition can't be run, but the (case break) before this definition can be run correctly.

  • error incomplete type used in nested name specifier

g++ gives this message if you've forward-declared a type, like this

class MyClass;

and then you try and access one of its members, like maybe:


g++ is complaining that it hasn't seen the body of class MyClass yet, so it has no way to know what MyClass::doSomething is.

(In C++ jargon, an "incomplete type" is a type that's been forward-declared but not yet defined.)

You can often fix this by adding the right #include at the top of the source file.

When reading a root file produced with root5.26/00d with root5.26/00, this error happen

The 5.26/00d is none year later update of 5.26/00

  • error in using proofError message:

Info in <TProofLite::MarkBad>:  events  |>...................| 0.00 %
 +++ Message from master at lxplus206.cern.ch : marking 0.0-lxplus206.cern.ch-1285753103-11416:-1 (0.0) as bad
 +++ Reason: undefined message in TProof::CollectInputFrom(...)

 +++ Most likely your code crashed
 +++ Please check the session logs for error messages either using
 +++ the 'Show logs' button or executing
 +++ root [] TProof::Mgr("lxplus206.cern.ch")->GetSessionLogs()->Display("*")

Error in <TPacketizerAdaptive::SplitPerHost>: The input list contains no elements

Solution: because m_goodRunListXmlFile doesn't exist.

1888    TDOMParser xmlparser;
1889 #if ROOT_VERSION_CODE >= ROOT_VERSION( 5, 17, 4 )
1890    xmlparser.SetReplaceEntities( kTRUE );
1891 #endif
1892    Int_t parseError = xmlparser.ParseFile( m_goodRunListXmlFile.c_str() );
1893    if( parseError ) {
1895       cout << "Loading of xml document \"" << m_goodRunListXmlFile
1896             << "\" failed";

Example of using TGraphErrors

    double sys_bt1    [5]={50, 55,  60,  65,  70 };     
    double sys_A_bt   [5]={0.718301,  0.861586,   0.855908,  0.907561,  0.858515  };
    double sys_A_bt_e [5]={0.107668,  0.0962074, 0.0879854,  0.0841657, 0.0797709 };

    TGraphErrors* sysAbt =new TGraphErrors(5, sys_bt1, sys_A_bt, 0, sys_A_bt_e );    
    sysAbt->SetTitle("A vs b tag efficiency");
    sysAbt->GetXaxis()->SetTitle(" b tag efficiency (%)");

Example to creat 2D histgram of variable bins

  • This example produce 2 2D histgram, divide one by the other and draw.
const  int    mptbins = 8;
const  int    metabins = 7;  
const Float_t mxbin[mptbins+1]={20.,25,30,35,40,50,70,120.,300};
const Float_t mybin[metabins+1]={-2.5,-1.35,-1.15,-0.1,0.1,1.15,1.35,2.5};

plot_Efficiency2D(ntuple_tt_3_d, "m_reco_effi_pteta_d", weight_3*data*semimu*"selmuon_true==1 && mu_true_found_rec>0 ",  weight_3*semimu*"selmuon_true==1",  "ptmuon_true", mptbins, mxbin, 0.001, "etamuon_true",metabins, mybin,1);

void plot_Efficiency2D(TTree* tree,char* hist, TCut cutup, TCut cutdw,  char* varntuplex, int binx, const Float_t* xbin ,float scalex=1, char* varntupley, int biny, const Float_t* ybin, float scaley=1){
   tmpupref=new TH2F("tmpupref", "tmpupref", binx,xbin, biny,ybin);
   GetHistFromNtuple2D(tree, cutup, "tmpupref",varntuplex,scalex, varntupley,scaley);
   TH2F* tmpdwref=new TH2F("tmpdwref", "tmpdwref", binx,xbin, biny,ybin);   
   GetHistFromNtuple2D(tree, cutdw, "tmpdwref",varntuplex, scalex, varntupley,scaley);

void GetHistFromNtuple2D( TTree* tree, TCut cut, char* histname, char* varntuplex,float scalex=1, char* varntupley, float scaley=1){
      char var[1000];
      sprintf( var , "(%s*%f):(%s*%f)>>%s", varntupley,scaley,varntuplex,scalex,histname);
      tree->Draw(var, cut,"goff");  

Options for drawing histgram

  • use gStyle->SetOptFit
 The type of information about fit parameters printed in the histogram
 statistics box can be selected via the parameter mode.
  The parameter mode can be = pcev  (default = 0111)
    p = 1;  print Probability
    c = 1;  print Chisquare/Number of degress of freedom
    e = 1;  print errors (if e=1, v must be 1)
    v = 1;  print name/values of parameters
  Example: gStyle->SetOptFit(1011);
           print fit probability, parameter names/values and errors.
    When "v"=1 is specified, only the non-fixed parameters are shown.
    When "v"=2 all parameters are shown.

  Note: gStyle->SetOptFit(1) means "default value", so it is equivalent to
  • Use gStyle->SetOptStat
 The type of information printed in the histogram statistics box
  can be selected via the parameter mode.
  The parameter mode can be = ksiourmen  (default = 000001111)
    k = 1;  kurtosis printed
    k = 2;  kurtosis and kurtosis error printed
    s = 1;  skewness printed
    s = 2;  skewness and skewness error printed
    i = 1;  integral of bins printed
    o = 1;  number of overflows printed
    u = 1;  number of underflows printed
    r = 1;  rms printed
    r = 2;  rms and rms error printed
    m = 1;  mean value printed
    m = 2;  mean and mean error values printed
    e = 1;  number of entries printed
    n = 1;  name of histogram is printed
  Example: gStyle->SetOptStat(11);
           print only name of histogram and number of entries.
           gStyle->SetOptStat(1101);  displays the name of histogram, mean value and RMS.
  WARNING: never call SetOptStat(000111); but SetOptStat(1111), 0001111 will
          be taken as an octal number !!
  WARNING: SetOptStat(1) is taken as SetOptStat(1111) (for back compatibility
           with older versions. If you want to print only the name of the histogram
           call SetOptStat(1000000001).
  NOTE that in case of 2-D histograms, when selecting just underflow (10000)
        or overflow (100000), the stats box will show all combinations
        of underflow/overflows and not just one single number!

use roofit and FFT with root

  do not have root access of the machine to make a private install area for FFTW, e.g. /home/myself/fftw

  1.  www.fftw.org for fft downloading
  2.  Untar fftw-XXX.tar.gz in /tmp, cd into the untarred directory
       ./configure --prefix=/home/myself/fftw CFLAGS=fPIC CXXFLAGS=fPIC
       ' followed by 'make install'.
       Substitute /home/myself/fftw with a directory of your choice. This
       procedure will install FFTW in the location designated by you

   3. in ROOT directory 
      configure --enable-fftw3 --with-fftw3-incdir=/home/myself/fftw/include --with-fftw3-libdir=/home/myself/fftw/lib  --enable-roofit
      Then run 'make'

xmanager can't farword plot to terminal

solution run xmanager-braodcast once to fix it.

using latex on plot

when you try to set textsize and let it show formulas on the plot, you need take care that textfont is correctly set. The text font is set by SetTextFont(n)

The text font code n is combination of the font number and the precision. Text font code = 10*fontnumber + precision Font numbers must be between 1 and 14.

The precision can be: precision = 0 fast hardware fonts (steps in the size) precision = 1 scalable and rotatable hardware fonts (see below) precision = 2 scalable and rotatable hardware fonts precision = 3 scalable and rotatable hardware fonts. Text size is given in pixels.

If the precison is 0 or 1, your latex will print blankly, without symbol transformation. for precison 0, 1 ,2 the text size means the percentage of the pad size, for 3, text size will be absolute pixals


use rootcore

error: #error This file requires compiler and library support for the ISO C++ 2011 standard. This support is currently experimental, and must be enabled with the -std=c++11 or -std=gnu++11 compiler options. #error This file requires compiler and library support for the solution: Because of an interference between the ROOT dictionary of the algorithm, and the way TChain tries to clean up at the end of the job, we have to completely hide the tool pointer from the dictionary generator for now. That's what the CINT expression is for. in your header file put the included as following

#ifndef CINT #include "MuonMomentumCorrections/MuonCalibrationAndSmearingTool.h" #endif

class MuonCalibrationAndSmearingTool;

#ifndef CINT CP::MuonCalibrationAndSmearingTool *m_muonCalibrationAndSmearingTool; //! #endif // not CINT

root Streaminfo

Error in <TStreamerInfo::Build:>: MyxAODAnalysis: ConfigureClass* has no streamer or dictionary, data member conf will not be saved

this error happen because ConfigureClass has no streaminfo definition, so don't know how to save into file.

when save a class into file, the file has to have streamerinfo defined, so the code knows how to decode the file when reading.

If you don't want to save the class into file, define this way
ConfigureClass* conf;  //!

//! tell that you don't write the class into file

working with stats box

void ToolHelper::DrawHist(TH1* hOri, TString xTitle, TString yTitle) {

  gStyle->SetOptStat(1);   //  must >0
  gStyle->SetOptFit(1111);  // what to set in stats box
  TH1* h = HistClone(hOri, "h");
  h->SetStats(1);     // tells that we create stats box for h
  int dim = h->GetDimension();
  if (dim==2) h = Hist2DTo1D(h, "hNew");
  double max, min;
  ResetHisMaxMin(h, max, min);

  h->GetYaxis()->SetRangeUser(min, max);
  SetMarkerColorSizeStyle(h, kBlue);
  if(xTitle!="") h->SetXTitle(xTitle);
  if(yTitle!="") h->SetYTitle(yTitle);
  h->Draw("e");   // when draw, stats box will created, DrawCopy doesn't work here
  gPad->Update();  // in non-interactive mode, you need this to force the draw happen.
  TPaveStats* stats1 =(TPaveStats*) h->FindObject("stats");  // retrieve the stats box from drawn hist
  cout<<"stats1: "<<stats1<<endl;
  stats1->Draw();  // draw it or change its place and draw.
  //delete h;

-- ChengguangZhu - 29 Nov 2007

Edit | Attach | Watch | Print version | History: r28 < r27 < r26 < r25 < r24 | Backlinks | Raw View | WYSIWYG | More topic actions
Topic revision: r28 - 2015-01-20 - ChengguangZhu
    • Cern Search Icon Cern Search
    • TWiki Search Icon TWiki Search
    • Google Search Icon Google Search

    Main All webs login

This site is powered by the TWiki collaboration platform Powered by PerlCopyright &© 2008-2022 by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
or Ideas, requests, problems regarding TWiki? use Discourse or Send feedback