Skip to content

Commit 323befe

Browse files
committed
Fix incorrect deallocation from PMR when memory was not aligned.
1 parent 9d0c12f commit 323befe

File tree

2 files changed

+35
-2
lines changed

2 files changed

+35
-2
lines changed

include/jsoncons/utility/heap_string.hpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -177,7 +177,7 @@ namespace utility {
177177

178178
std::size_t mem_size = ptr->align_pad_ + aligned_size(ptr->length_*sizeof(char_type));
179179
byte_allocator_type byte_alloc(ptr->get_allocator());
180-
byte_alloc.deallocate(p,mem_size + ptr->offset_);
180+
byte_alloc.deallocate(p,mem_size);
181181
}
182182
}
183183
};

test/corelib/src/utility/heap_string_tests.cpp

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,14 +31,45 @@ TEST_CASE("heap_string test")
3131
#if defined(JSONCONS_HAS_POLYMORPHIC_ALLOCATOR) && JSONCONS_HAS_POLYMORPHIC_ALLOCATOR == 1
3232
#include <memory_resource>
3333

34+
class checked_resource : public std::pmr::memory_resource
35+
{
36+
public:
37+
explicit checked_resource(std::pmr::memory_resource* upstream = std::pmr::get_default_resource())
38+
: upstream_(upstream)
39+
{
40+
}
41+
42+
ssize_t allocated = 0;
43+
44+
protected:
45+
void* do_allocate(std::size_t bytes, std::size_t alignment) override
46+
{
47+
allocated += bytes;
48+
return upstream_->allocate(bytes, alignment);
49+
}
50+
51+
void do_deallocate(void* p, std::size_t bytes, std::size_t alignment) override
52+
{
53+
allocated -= bytes;
54+
upstream_->deallocate(p, bytes, alignment);
55+
}
56+
57+
bool do_is_equal(const memory_resource& other) const noexcept override { return this == &other; }
58+
59+
private:
60+
std::pmr::memory_resource* upstream_;
61+
};
62+
63+
3464
TEST_CASE("heap_string with polymorphic allocator test")
3565
{
3666
using heap_string_factory_type = jsoncons::utility::heap_string_factory<char, null_type, std::pmr::polymorphic_allocator<char>>;
3767
using pointer = typename heap_string_factory_type::pointer;
3868

3969
char buffer[1024] = {}; // a small buffer on the stack
4070
std::pmr::monotonic_buffer_resource pool1{ std::data(buffer), std::size(buffer) };
41-
std::pmr::polymorphic_allocator<char> alloc(&pool1);
71+
checked_resource checked(&pool1);
72+
std::pmr::polymorphic_allocator<char> alloc(&checked);
4273

4374
std::string s1("Hello World 1");
4475
pointer ptr1 = heap_string_factory_type::create(s1.data(), s1.length(), null_type(), alloc);
@@ -52,6 +83,8 @@ TEST_CASE("heap_string with polymorphic allocator test")
5283

5384
heap_string_factory_type::destroy(ptr1);
5485
heap_string_factory_type::destroy(ptr2);
86+
87+
CHECK(checked.allocated == 0);
5588
}
5689

5790

0 commit comments

Comments
 (0)