My destructor is causing my program to crash

In summary, the author has trouble with a copy constructor in a class that uses a built-in pointer and finds a way to work around the problem by making the member variable a std::string instead.
  • #1
JonnyG
233
30
Below is my code. The include directives and the using std::* declarations have been removed for brevity:

C++:
class HasPtr {
    friend void swap(HasPtr&, HasPtr&);
public:
    HasPtr(const std::string &s = string()): ps(new string(s)), i(0) {}
    HasPtr(const string &s, const int &j) : ps(new string(s)), i(j) {}
    HasPtr(const int &j) : ps(new string()), i(j) {}
    HasPtr(const HasPtr &hp) : ps(hp.ps), i(hp.i) {} //copy constructor
   
    //copy-assignment operator
    HasPtr& operator=(HasPtr rhs) {
        swap(*this, rhs);
        return *this;
    }

    bool operator<(const HasPtr &rhs) {
        return this->i < rhs.i;
    }  

    //destructor
    ~HasPtr() {
        delete ps;
    }
       
    std::string *ps;
    int i;
};

inline void swap(HasPtr &hp1, HasPtr &hp2) {
    using std::swap;
    swap(hp1.ps, hp2.ps);
    swap(hp1.i, hp2.i);
}

int main() {
    HasPtr p1(32), p2(44);
    vector<HasPtr> v {p1, p2};
}

Whenever I run this program, it crashes. I ran my debugger and I also ran a memory-checking program on the compiled executable and it looks as if my HasPtr destructor is causing problems. It appears to me that when I initialize my vector, it makes a local copy of p1 and p2 and when the initializing is done, it runs my destructor on these local copies of p1 and p2, resulting in the other p1 and p2 objects (the original ones in the main scope) containing dangling pointers and thus crashing the program.

My destructor must delete the memory pointed to by the object, because otherwise once my object is deleted, the pointer will be deleted but the actual memory itself won't be freed, so I will have a memory leak.

Given this, how can I create a vector of HasPtr objects? Every method for putting HasPtr objects into the vector results in temporaries being created, which seems to be what is causing the problem in the first place.

EDIT: This class is the result of the exercises in my book, and it is required that I use a built-in pointer in this exercise, so I cannot use a smart pointer to replace the built-in pointer.
 
Technology news on Phys.org
  • #2
There is a clear issue in your copy constructor which, when used, will lead to the bug you see.
 
  • Like
Likes jbunniii and JonnyG
  • #3
Filip Larsen said:
There is a clear issue in your copy constructor which, when used, will lead to the bug you see.

I literally just came into this thread to make an update that I figured it out. I changed,

ps(hp.ps)

to

ps(new string(*hp.ps))
 
  • Like
Likes Filip Larsen
  • #4
Using smart pointers avoids problems with mismatched new/delete.
C++:
#include <memory>
#include <string>
#include <vector>

class HasPtr {
    friend void swap(HasPtr&, HasPtr&);
public:
    HasPtr(const std::string &s = std::string()): ps(std::make_unique<std::string>(s)), i(0) {}
    HasPtr(const std::string &s, const int &j) : ps(std::make_unique<std::string>(s)), i(j) {}
    HasPtr(const int &j) : ps(std::make_unique<std::string>()), i(j) {}
    //copy constructor
    HasPtr(const HasPtr &hp)
    : i(hp.i)
    {
        if (hp.ps != nullptr) {
            ps = std::make_unique<std::string>(*hp.ps);
        }
    }

    //copy-assignment operator and operator< unchanged from raw pointer implementation:
    HasPtr& operator=(HasPtr rhs) {
        swap(*this, rhs);
        return *this;
    }

    bool operator<(const HasPtr &rhs) {
        return this->i < rhs.i;
    }

    //destructor
    ~HasPtr() {
        // nothing to do, unique_ptr destroys the object it points to
    }

    std::unique_ptr<std::string> ps;
    int i;
};
Or just avoid the whole mess by making the member variable a std::string instead of a pointer to a std::string.
 

1. Why is my destructor causing my program to crash?

A destructor is a special function in an object-oriented programming language that is responsible for releasing any resources allocated by an object. If the destructor is not properly written or executed, it can lead to memory leaks or other issues that can cause a program to crash.

2. How do I fix a crashing destructor?

Fixing a crashing destructor can be a complex process and will depend on the specific code and language being used. Some common solutions include debugging the code to identify the source of the issue, properly handling exceptions, and ensuring that all resources are correctly released in the destructor.

3. Can a destructor cause memory leaks?

Yes, a destructor can cause memory leaks if it is not properly written or executed. This can happen if the destructor does not release all allocated resources or if there are any errors or exceptions that prevent the destructor from completing its tasks.

4. How can I prevent my destructor from crashing my program?

To prevent a destructor from crashing your program, it is important to properly handle exceptions and ensure that all resources are correctly released. It is also helpful to thoroughly test the code and use debugging tools to identify and fix any issues before they lead to a program crash.

5. Are there any alternative methods to using a destructor?

Yes, there are alternative methods to using a destructor. Some languages, such as Java, use automatic garbage collection instead of destructors to manage memory and release resources. Other languages may use different techniques, such as smart pointers, to handle resource management. It is important to research and understand the specific language and its best practices for managing resources.

Similar threads

  • Programming and Computer Science
Replies
5
Views
818
  • Programming and Computer Science
Replies
19
Views
979
  • Programming and Computer Science
3
Replies
89
Views
4K
  • Programming and Computer Science
Replies
1
Views
647
  • Programming and Computer Science
Replies
5
Views
1K
  • Programming and Computer Science
Replies
5
Views
885
  • Programming and Computer Science
3
Replies
89
Views
4K
  • Programming and Computer Science
Replies
7
Views
3K
  • Programming and Computer Science
4
Replies
118
Views
6K
  • Programming and Computer Science
Replies
11
Views
2K
Back
Top