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.
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.