Should pmr::memory_resource::allocate(n, a) use bit_ceil(a)?
Jonathan Wakely
jwakely@redhat.com
Thu Jul 3 23:45:49 GMT 2025
On Fri, 4 Jul 2025 at 00:40, Jonathan Wakely <jwakely@redhat.com> wrote:
>
> I should probably adopt Martin's patch from
> https://gcc.gnu.org/PR86878 and finish it, so that we get warnings for
> invalid non-power-of-two alignments passed to allocation functions,
> but since we don't have that ...
>
> Would it be a good idea for pmr::memory_resource::allocate(n, a) to call:
> do_allocate(n, bit_ceil(a))
> ?
>
> That would ensure that the virtual override of do_allocate is always
> called with a valid alignment, even if the user violates the
> precondition of memory_resource::allocate.
>
> When the argument is a constant, the compiler can optimize bit_ceil(a)
> away if it knows it's already a power of two.
>
> Without this, I'm tempted to put an assertion or do the bit_ceil(a) in
> each override of do_allocate, to avoid potential UB caused by invalid
> alignment values.
This would prevent a debugging memory resource from detecting invalid
alignments, because the derived type would always see valid
alignments. That would prevent such a resource from detecting bugs in
the program.
But it would render such bugs harmless, which might be better for safety.
Again, I should probably just implement the warning so that the
compiler detects those bugs (at least for cases where the requested
alignment is a constant).
More information about the Libstdc++
mailing list