[Bug libstdc++/71684] New: Memory leak with std::mutex and std::lock_guard on freebsd

plongstaff at sandvine dot com gcc-bugzilla@gcc.gnu.org
Tue Jun 28 14:47:00 GMT 2016


https://gcc.gnu.org/bugzilla/show_bug.cgi?id=71684

            Bug ID: 71684
           Summary: Memory leak with std::mutex and std::lock_guard on
                    freebsd
           Product: gcc
           Version: 4.9.1
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: libstdc++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: plongstaff at sandvine dot com
  Target Milestone: ---

On freebsd, pthread_mutex_t is a pointer to 'struct pthread_mutex'.
PTHREAD_MUTEX_INITIALIZER is defined as NULL. On freebsd, the code:

{
    std::mutex m;
    std::lock_guard lg(m);
}

will leak. 'm' will have _M_mutex initialized to NULL. When the std::lock_guard
constructor calls gthread_mutex_lock() which calls pthread_mutex_lock(), a
'struct pthread_mutex' will be created using calloc() and then locked. The
std::lock_guard destructor will unlock the mutex. However, since
std::mutex_base has:

  // Common base class for std::mutex and std::timed_mutex
  class __mutex_base
  {
  protected:
    typedef __gthread_mutex_t                   __native_type;

#ifdef __GTHREAD_MUTEX_INIT
    __native_type  _M_mutex = __GTHREAD_MUTEX_INIT;

    constexpr __mutex_base() noexcept = default;
#else
    __native_type  _M_mutex;

    __mutex_base() noexcept
    {
      // XXX EAGAIN, ENOMEM, EPERM, EBUSY(may), EINVAL(may)
      __GTHREAD_MUTEX_INIT_FUNCTION(&_M_mutex);
    }

    ~__mutex_base() noexcept { __gthread_mutex_destroy(&_M_mutex); }
#endif

    __mutex_base(const __mutex_base&) = delete;
    __mutex_base& operator=(const __mutex_base&) = delete;
  };

and __GTHREAD_MUTEX_INIT is defined as NULL, there is no destructor to destroy
the mutex. Therefore, that memory is leaked.


More information about the Gcc-bugs mailing list