Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: s/::f()/::h()/g;

...

Despite the presence of a user-declared destructor, C will have an implicitly defaulted copy constructor defined for it, and this defaulted copy constructor will copy the pointer value stored in p, resulting in a double-free: the first free happens when g() exits, and the second free happens when fh() exits.

Code Block
bgColor#FFCCCC
langcpp
struct P {};

class C {
  P *p;
  
public:
  C(P *p) : p(p) {}
  ~C() { delete p; }  
  
  void f() {}
};

void g(C c) {
  c.f();
}

void fh() {
  P *p = new P;
  C c(p);
  g(c);
}

...

Code Block
bgColor#ccccff
langcpp
struct P {};

class C {
  P *p;
  
public:
  C(P *p) : p(p) {}
  C(const C&) = delete;
  ~C() { delete p; }
 
  void operator=(const C&) = delete;
  
  void f() {}
};

void g(C &c) {
  c.f();
}

void fh() {
  P *p = new P;
  C c(p);
  g(c);
}

...