]> git.ipfire.org Git - thirdparty/gcc.git/commit
libstdc++: fix a dangling reference crash in ranges::is_permutation [PR118160]
authorGiuseppe D'Angelo <giuseppe.dangelo@kdab.com>
Thu, 6 Feb 2025 14:24:17 +0000 (14:24 +0000)
committerJonathan Wakely <jwakely@redhat.com>
Fri, 6 Jun 2025 09:14:12 +0000 (10:14 +0100)
commit63be00fe4cad2552edcda863087adcce0b2aa236
tree595e09c6ccf430604af11dec5eae00076bc979bc
parent26e891dd7e9600a3f3a1acbdfe0bb39a44b8a65d
libstdc++: fix a dangling reference crash in ranges::is_permutation [PR118160]

The code was caching the result of `invoke(proj, *it)` in a local
`auto &&` variable. The problem is that this may create dangling
references, for instance in case `proj` is `std::identity` (the common
case) and `*it` produces a prvalue: lifetime extension does not
apply here due to the expressions involved.

Instead, store (and lifetime-extend) the result of `*it` in a separate
variable, then project that variable. While at it, also forward the
result of the projection to the predicate, so that the predicate can
act on the proper value category.

libstdc++-v3/ChangeLog:

PR libstdc++/118160
PR libstdc++/100249
* include/bits/ranges_algo.h (__is_permutation_fn): Avoid a
dangling reference by storing the result of the iterator
dereference and the result of the projection in two distinct
variables, in order to lifetime-extend each one.
Forward the projected value to the predicate.
* testsuite/25_algorithms/is_permutation/constrained.cc: Add a
test with a range returning prvalues. Test it in a constexpr
context, in order to rely on the compiler to catch UB.

Signed-off-by: Giuseppe D'Angelo <giuseppe.dangelo@kdab.com>
(cherry picked from commit 2a2bd96d0d2109384a0eedde843ba811d2e18738)
libstdc++-v3/include/bits/ranges_algo.h
libstdc++-v3/testsuite/25_algorithms/is_permutation/constrained.cc