refactor: Avoid UB from std::distance with nullptr in PoolAllocator #34161

pull l0rinc wants to merge 1 commits into bitcoin:master from l0rinc:l0rinc/pool-allocator-ub changing 1 files +7 −3
  1. l0rinc commented at 1:01 pm on December 28, 2025: contributor

    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.

  2. refactor: Avoid UB from `std::distance` with `nullptr` in `PoolAllocator`
    Calling `std::distance(nullptr, nullptr)` is undefined behavior per the C++ standard [iterator.requirements.general](https://eel.is/c++draft/iterator.requirements.general#7):
    > 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](https://eel.is/c++draft/iterator.operations#4):
    > Preconditions: last is reachable from first
    
    Check for `nullptr` before calling `std::distance` to avoid this UB. This check only affects the very first call, after which the pointers are initialized.
    b9ffd11eec
  3. DrahtBot added the label Refactoring on Dec 28, 2025
  4. DrahtBot commented at 1:01 pm on December 28, 2025: contributor

    The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.

    Code Coverage & Benchmarks

    For details see: https://corecheck.dev/bitcoin/bitcoin/pulls/34161.

    Reviews

    See the guideline for information on the review process. A summary of reviews will appear here.

  5. l0rinc marked this as ready for review on Dec 28, 2025

github-metadata-mirror

This is a metadata mirror of the GitHub repository bitcoin/bitcoin. This site is not affiliated with GitHub. Content is generated from a GitHub metadata backup.
generated: 2026-01-02 00:13 UTC

This site is hosted by @0xB10C
More mirrored repositories can be found on mirror.b10c.me