Why segfault occurs when SetBranchAddress without initializing pointer to nullptr

Dear experts

I always got segfault if I declare something like std::vector<TVector3> a; and then SetBranchAddress("a", &a);, if I didn’t initialize the pointer to nullptr first. But I found in source code it will set the pointer to nullptr forcibly anyway, so why segfault occurs?
I mean here

Yes, you must initialize (all) pointers to nullptr or a valid value otherwise the behavior of the problem is usually undetermined. In the case of SetBranchAddress it can not know if the random value held by the pointer (if you do not explicitly assign it) is a valid address or not. It has no choice but to assume it is a valid address and when it is not it will lead to a crash.

Thank you for your answer, I understand that I must do it in principle, but in the source code I mentioned:

Int_t TTree::SetBranchAddress(const char* bname, void* addr, TBranch** ptr)
 8377{
 8378   TBranch* branch = GetBranch(bname);
 8379   if (!branch) {
 8380      if (ptr) *ptr = nullptr;
 8381      Error("SetBranchAddress", "unknown branch -> %s", bname);
 8382      return kMissingBranch;
 8383   }
 8384   return SetBranchAddressImp(branch,addr,ptr);
 8385}

it will be set to nullptr anyway, isn’t it?

Note that ptr is a pointer to a pointer. If there is no branch, the pointer that ptr points to will be set to nullptr in the code that you linked:

if (ptr) *ptr = nullptr;

You can see this because ptr is de-referenced like *ptr, which results in a segfault if ptr is not pointing to a valid memory location. If you set it to nullptr before, there is no de-referencing happening because the if (ptr) will be false. But if it’s not initialized, it contains a random number and de-referencing results in a segfault.

Ah, I see. It’s a pointer to a pointer and I need to set the upstream pointer to nullptr. Thank you!