Problem
Calling std::distance(nullptr, nullptr) is undefined behavior per the C++ standard iterator.requirements.general:
Iterators can also have singular values that are not associated with any sequence. Results of most expressions are undefined for singular values.
Null pointers are singular iterators not associated with any sequence, so they cannot form a valid range required by std::distance:
Preconditions: last is reachable from first
While expr.add#5.1 defines pointer subtraction for null pointers:
If P and Q both evaluate to null pointer values, the value is 0
This applies to direct pointer arithmetic (nullptr - nullptr), not to std::distance, which has additional preconditions requiring non-singular iterators.
Fix
Checked for nullptr before calling std::distance to avoid this undefined behavior.
This check only affects the very first call, after which the pointers are initialized.