PR #2074: docs: warn against using &v[0] on empty vectors in MakeSpan Imported from GitHub PR https://github.com/abseil/abseil-cpp/pull/2074 This PR adds a warning note to the documentation of absl::MakeSpan and absl::MakeConstSpan in absl/types/span.h regarding a common undefined behavior (UB) pitfall when constructing spans from std::vector (or other dynamic containers). #### The Problem Developers frequently try to initialize spans using array-like pointer boundaries: absl::MakeSpan(&v[0], v.size()); However, if v is empty, dereferencing v[0] to obtain its address is undefined behavior in C++. Similarly, attempting to use &v[v.size()] to obtain a range-end pointer also triggers UB. #### The Fix This documentation update advises developers to use .data() instead: absl::MakeSpan(v.data(), v.size()); Or simply pass the container directly to the container overload of MakeSpan : absl::MakeSpan(v); This addresses the common pitfall discussed in Issue #1334. ### Related Issues: Closes #1334 Merge aaee4d4d7679e1308a19a30d1e2d6e78cadf7618 into 713ec92aa4d23a6e40e4878a5527d93b32939fd6 Merging this change closes #2074 COPYBARA_INTEGRATE_REVIEW=https://github.com/abseil/abseil-cpp/pull/2074 from Madhav1729:docs-makespan-vector-ub aaee4d4d7679e1308a19a30d1e2d6e78cadf7618 PiperOrigin-RevId: 930034154 Change-Id: I6a518b39c61ba4050130895aa8dcb5656a95f31c
diff --git a/absl/types/span.h b/absl/types/span.h index 3b291a9..c33e294 100644 --- a/absl/types/span.h +++ b/absl/types/span.h
@@ -719,6 +719,9 @@ // return absl::MakeSpan(&array[0], num_elements_); // } // +// NOTE: To avoid undefined behavior if the container is empty, use `.data()` +// or pass the container directly instead of using `&v[0]` or `&v[v.size()]`. +// template <int&... ExplicitArgumentBarrier, typename T> constexpr Span<T> MakeSpan(T* absl_nullable ptr ABSL_ATTRIBUTE_LIFETIME_BOUND, size_t size) noexcept {