http://gcc.gnu.org/bugzilla/show_bug.cgi?id=49728

           Summary: g++ -> int object in memory deleted multiple times: no
                    runtime error
           Product: gcc
           Version: 4.5.2
            Status: UNCONFIRMED
          Severity: minor
          Priority: P3
         Component: c++
        AssignedTo: unassig...@gcc.gnu.org
        ReportedBy: b7756...@klzlk.com


Created attachment 24749
  --> http://gcc.gnu.org/bugzilla/attachment.cgi?id=24749
source code

Hi!

Below is an example, where an int-memory-object is deleted 3 times.
No runtime errors occur?

Is this a bug?
Thanks.



The example uses smart-pointers.
(source sode attached)
The int-memory-object (pointed-to by ip) is deleted 3 times: see lines 59, 62,
67

The deleted int-memory-object, can still be accessed: see lines 61, 64, 68



// line 1
// Below an int-object is created with new int(1)
// Usually a runtime error occurs if an object is deleted 2 or more times.
// But in the course of the execution, the object is deleted 3 times --> Why
does no runtime error occur?


#include <iostream>

using std::cout;
using std::endl;

class U_a
{
  friend class B;
  U_a(int *p) : ip(p), use(1) {}
  ~U_a() {
    std::cout << "Delete " << ip << std::endl;
    delete ip;
  }
  int *ip;
  size_t use; // use-counter, used by smart-pointer...
};

class B // uses smart pointers
{
public:
  B(int *p) : ptr(new U_a(p)) {}
  B(const B &rhs) : ptr(rhs.ptr) {
    ++ptr->use;
  }
  B &operator=(const B &rhs) {
    ++rhs.ptr->use;
    if (--ptr->use == 0)
      delete ptr;
    ptr = rhs.ptr;
    return *this;
  }
  int get_ip_val() {
    return *ptr->ip;
  }
  ~B() {
    if (--ptr->use == 0)
      delete ptr;
  }
private:
  U_a *ptr;
};


int main()
{

  int *ip = new int(1); // created "object-pointed-to-by ip" and give it
initial value 1
  {
    B b1(ip);
    {
      B b2(ip);         // deliberate bad use of smart-pointer class. This is
not the copy constructor! ;)
      cout << "Val: " << b1.get_ip_val() << endl;
    }                   // b2's destructor has run and deleted
"object-pointed-to-by ip"!

    cout << "Val: " << b1.get_ip_val() << endl; // 1)*** Why can we still get
"object-pointed-to-by ip"? Why is there no runtime error?
  }          // 2)*** b1's destructor has run and deleted "object-pointed-to-by
ip" the second time!!! Why is there still no runtime error?

  *ip = 4;   // 3)*** Why is there still no runtime error?

  std::cout << "Delete " << ip << std::endl;
  delete ip; // here we delete "object-pointed-to-by ip" a 3rd time     4)***
Why is there still no runtime error?
  *ip = 5;   // 5)*** Why is there still no runtime error?

  return 0;
}

Reply via email to