[Bug c++/77312] Lambda that deletes itself accesses freed memory, but only if class is templated

redi at gcc dot gnu.org gcc-bugzilla@gcc.gnu.org
Mon Aug 22 10:08:00 GMT 2016


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

Jonathan Wakely <redi at gcc dot gnu.org> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
           Keywords|                            |wrong-code
             Status|UNCONFIRMED                 |NEW
   Last reconfirmed|                            |2016-08-22
            Version|unknown                     |5.4.1
     Ever confirmed|0                           |1

--- Comment #4 from Jonathan Wakely <redi at gcc dot gnu.org> ---
Reduced:

struct function_impl_base {
  virtual ~function_impl_base() = default;
  virtual void invoke() = 0;
};

template<typename F>
struct function_impl : function_impl_base {
  function_impl(F f) : f(f) { }
  void invoke() { f(); }
  F f;
};

struct function
{
  template<typename F>
    function(F f) : impl(new function_impl<F>{f}) { }
  ~function() { delete impl; }
  function(const function&) = delete;
  function_impl_base* impl;
  void operator()() { impl->invoke(); }
};

template <class U>
struct LambdaHolder {
    LambdaHolder() : lambda_{[this]() { delete this; }} {
    }
    void Run() {
        lambda_();
    }
    function lambda_;
};

int main() {
    LambdaHolder<int>* l = new LambdaHolder<int>();
    l->Run();
}


There's no reason this should need to access the freed memory. Clang and EDG
don't.


More information about the Gcc-bugs mailing list