https://gcc.gnu.org/bugzilla/show_bug.cgi?id=89303
Bug ID: 89303 Summary: memory leak with shared_ptr and enable_shared_from_this Product: gcc Version: unknown Status: UNCONFIRMED Severity: normal Priority: P3 Component: c++ Assignee: unassigned at gcc dot gnu.org Reporter: adl at gnu dot org Target Milestone: --- I'm not sure if this issue is compiler or library related, but since changing -O into -O0 or -O2 hides the issue, I'm assuming its the compiler. This is g++ 8.2.0-20 from Debian unstable (SVN 20190209 (r268721) from the gcc-8-branch) running on amd64. % cat issue.c #include <memory> class blob final: public std::enable_shared_from_this<blob> { int* data; public: blob() { data = new int; } ~blob() { delete data; } }; static int bar(std::shared_ptr<blob>) { return 0; } int main() { std::shared_ptr<blob> tg = std::make_shared<blob>(); return bar(tg); } % g++ -Wall -g -O issue.cc % valgrind -q --leak-check=full ./a.out ==13174== 40 bytes in 1 blocks are definitely lost in loss record 1 of 1 ==13174== at 0x4835DEF: operator new(unsigned long) (vg_replace_malloc.c:334) ==13174== by 0x1092F5: allocate (new_allocator.h:111) ==13174== by 0x1092F5: allocate (alloc_traits.h:436) ==13174== by 0x1092F5: __allocate_guarded<std::allocator<std::_Sp_counted_ptr_inplace<blob, std::allocator<blob>, (__gnu_cxx::_Lock_policy)2> > > (allocated_ptr.h:97) ==13174== by 0x1092F5: __shared_count<blob, std::allocator<blob> > (shared_ptr_base.h:675) ==13174== by 0x1092F5: std::__shared_ptr<blob, (__gnu_cxx::_Lock_policy)2>::__shared_ptr<std::allocator<blob>>(std::_Sp_alloc_shared_tag<std::allocator<blob> >) (shared_ptr_base.h:1342) ==13174== by 0x109185: shared_ptr<std::allocator<blob> > (shared_ptr.h:359) ==13174== by 0x109185: allocate_shared<blob, std::allocator<blob> > (shared_ptr.h:706) ==13174== by 0x109185: make_shared<blob> (shared_ptr.h:722) ==13174== by 0x109185: main (issue.cc:20) ==13174== I've confirmed that this leak exist using GNU libc's mtrace(), i.e., this is not a valgrind bug. Note that changing -O into -O0 or -O2 removes the leak. This is a reduced test case from a larger project that started leaking memory after I upgraded Debian unstable's g++-8 package from version 8.2.0-13 to version 8.2.0-16. I also have some tests that started raising bad_weak_ptr exceptions, but so far I haven't reduced those. Note that 8.2.0-16 includes the patch for libstdc++/88782 ; could this be related?