[PATCH] D47344: LWG 2843 "Unclear behavior of std::pmr::memory_resource::do_allocate()"

Arthur O'Dwyer via Phabricator via cfe-commits cfe-commits at lists.llvm.org
Thu May 24 19:50:13 PDT 2018


Quuxplusone updated this revision to Diff 148540.
Quuxplusone added a comment.

Oops. If we do get an underaligned result, let's not leak it!


Repository:
  rCXX libc++

https://reviews.llvm.org/D47344

Files:
  src/experimental/memory_resource.cpp


Index: src/experimental/memory_resource.cpp
===================================================================
--- src/experimental/memory_resource.cpp
+++ src/experimental/memory_resource.cpp
@@ -8,6 +8,7 @@
 //===----------------------------------------------------------------------===//
 
 #include "experimental/memory_resource"
+#include "memory"
 
 #ifndef _LIBCPP_HAS_NO_ATOMIC_HEADER
 #include "atomic"
@@ -23,18 +24,37 @@
 
 // new_delete_resource()
 
+#ifdef _LIBCPP_HAS_NO_ALIGNED_ALLOCATION
+static bool is_aligned_to(void *ptr, size_t align)
+{
+    void *p2 = ptr;
+    size_t space = 1;
+    void *result = _VSTD::align(align, 1, p2, space);
+    return (result == ptr);
+}
+#endif
+
 class _LIBCPP_TYPE_VIS __new_delete_memory_resource_imp
     : public memory_resource
 {
 public:
     ~__new_delete_memory_resource_imp() = default;
 
 protected:
     virtual void* do_allocate(size_t __size, size_t __align)
-        { return _VSTD::__libcpp_allocate(__size, __align); /* FIXME */}
+    {
+        void *result = _VSTD::__libcpp_allocate(__size, __align);
+#ifdef _LIBCPP_HAS_NO_ALIGNED_ALLOCATION
+        if (__size != 0 && !is_aligned_to(result, __align)) {
+            _VSTD::__libcpp_deallocate(result, __align);
+            __throw_bad_alloc();
+        }
+#endif
+        return result;
+    }
 
     virtual void do_deallocate(void * __p, size_t, size_t __align)
-        { _VSTD::__libcpp_deallocate(__p, __align); /* FIXME */ }
+        { _VSTD::__libcpp_deallocate(__p, __align); }
 
     virtual bool do_is_equal(memory_resource const & __other) const _NOEXCEPT
         { return &__other == this; }


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D47344.148540.patch
Type: text/x-patch
Size: 1634 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/cfe-commits/attachments/20180525/7771aa7b/attachment.bin>


More information about the cfe-commits mailing list