The correct way to allocate memory for std :: shared_ptr

I have implemented a function in which a personality is given to me and beyond my control. He returns std::shared_ptr<const void>. In the function, I allocate an arbitrary amount of memory and return access to it, although shared_ptr.

Memory allocation is done with new unsigned char[123]. The problem is that valgrind detects a mismatch between using new and deleted options. Although I use new[](unsigned)memory allocation, the shared_ptr destructor uses delete(void*)it to free it, and valgrind warns when you use the "wrong" deactivator to allocate it.

More practical, I wrote this test case to show what I mean:

TEST(Example, Test1)
{
  unsigned char* mem = new unsigned char[123];
  std::shared_ptr<const void> ptr(mem);
}

Valgrind report says

==45794== Mismatched free() / delete / delete []
==45794==    at 0x4C2A64B: operator delete(void*) (vg_replace_malloc.c:576)
==45794==    by 0x40B7B5: _M_release (shared_ptr_base.h:150)
==45794==    by 0x40B7B5: ~__shared_count (shared_ptr_base.h:659)
==45794==    by 0x40B7B5: ~__shared_ptr (shared_ptr_base.h:925)
==45794==    by 0x40B7B5: ~shared_ptr (shared_ptr.h:93)
==45794==    by 0x40B7B5: Example_Test1_Test::TestBody() (test.cc:108)
==45794==  Address 0x5cb6290 is 0 bytes inside a block of size 123 alloc'd
==45794==    at 0x4C29CAF: operator new[](unsigned long) (vg_replace_malloc.c:423)
==45794==    by 0x40B72E: Example_Test1_Test::TestBody() (test.cc:107)

I want, if possible, to avoid valgrind filters.

std::shared_ptr<const void>?

+4
1

shared_ptr<T> a T, , deleter delete p;. new, , delete[] p;. std::default_delete, :

return static_pointer_cast<const void>(
    std::shared_ptr<unsigned char>(
        new unsigned char[N],
        std::default_delete<unsigned char[]>()));

( , .)

++ 17, shared_ptr ,

shared_ptr<unsigned char[]>(new unsigned char[N])

( ).

+13

Source: https://habr.com/ru/post/1671775/


All Articles