Equal operator of TGraph


following code crashes:

int main() {
TGraph *g1 = new TGraph(0);
TGraph *g2 = new TGraph(0);
*g2 = *g1;
return 0;

Thanks for any help.


Hi. Really :laughing:

IMHO That’s because of very “clever” implementation of operator = :

if(this!=&gr) {
      fNpoints = gr.fNpoints;
      fMaxSize = gr.fMaxSize;
      if (gr.fFunctions) fFunctions = (TList*)gr.fFunctions->Clone();
      else fFunctions = new TList;
      fHistogram = new TH1F(*fHistogram);//I guess, "interesting" (for your case) place is here
      fMinimum = gr.fMinimum;
      fMaximum = gr.fMaximum;
      if (!fMaxSize) {
         fX = fY = 0;//IMHO and here ("interesting" for someone else)
         return *this;
      } else {
         fX = new Double_t[fMaxSize]; //IMHO and here ("interesting" for someone else)
         fY = new Double_t[fMaxSize];
      Int_t n = gr.GetN()*sizeof(Double_t);
      memcpy(fX, gr.fX, n);
      memcpy(fY, gr.fY, n);
   return *this;

fHistogram = new TH1F(*fHistogram); looks strange.
If fHistogram is 0, it causes crash, otherwise it causes a memory leak.

fX and fY can also cause memory leaks easily.
fX and fY are allocated without freeing. Maybe we have to free fX and fY before calling operator= when fNPoint is not 0.
(This is not relevant to Matthias’s problem)