Copy a hist from a tree

Hi experts,
I have a problem here:
I want to copy a hist from a tree.This is what I try to do:
(following this link: How to recover an object in a TTree?)

TH1F* getHist(string file, string treename,string name, int type, int color){
  TFile* tfile = new TFile(file.c_str());
   auto tree = (TTree*) tfile->Get(treename.c_str());
   TH1F* hist = 0; 
   return hist;

I am not sure if it’s fine. Because I met a problem:

  “ Error in <HandleInterpreterException>: Trying to dereference null pointer or trying to call routine taking non-null arguments.”

Could you please take a look at the problem? Thanks a lot!

ROOT Version: Not Provided
Platform: Not Provided
Compiler: Not Provided

Have you checked if name.c_str() is valid and you have a branch named with that name in your tree ?

Thanks! Yes,I have it in the tree.

I usually also add a SetDirectory(0) in the call to get the Hist, not sure if it is the recommended way, but in principle it disconmects the object to be linked to a file, so you can close the TFile inside the method

Thanks a lot! Finally, I turned back to the usual way => fill a new histogram again.