Use of function TH1::Copy()

Hello,

The function below should copy histograms h_vec to f_vec and then f_vec will be modified. I’m familiar with Clone() function by I’d like to try Copy() function to see the diference. The code compiles under Root but segmintation violation ocures when running. Could someone help me to understand why?

void calc_field (vector<TH2D*> &h_vec, vector<TH2D*> &f_vec)
{
   for (unsigned i=0; i<h_vec.size(); i++)
   {
      f_vec.push_back(0);
      f_vec.back()->Copy(*h_vec.at(i));
   }
   return;
}

Thanks in advance!

Solved with help of my colleagues. Copy() gets the reference to corresponding object and cannot work with null-pointer. And also the direction in the function is reverse. Thus the correct code is

void calc_field (vector<TH2D*> &h_vec, vector<TH2D*> &f_vec) 
{
   for (unsigned i=0; i<h_vec.size(); i++)
   {
      f_vec.push_back(new TH2D());
      h_vec.at(i)->Copy(*f_vec.back());

   }
   return;
}

Hi @sqrt91,
and welcome to the ROOT forum! Indeed you were calling a method on a nullptr, that’s a recipe for trouble.

Marked the thread as solved.
Cheers,
Enrico

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