0

I am struggeling with a memory error when calling the destructor of the folowing class:

class Point
{
private:
    int dimensions;
    double *values;

public:
    Point(const int dim);
    Point(const Point &that);
    ~Point();
    Point &operator=(const Point &that);
    double operator[](int i) const;
    int dim() const;
    void print();
};

The constructor is implemented as follows

Point::Point(const int dim) : dimensions(dim)
{
    values = new double[dim];
    for (int i = 0; i < dim; i++)
    {
        values[i] = 0.0;
    }
};

and the destructor as

Point::~Point()
{
    delete[] values;
};

Unfortunately, when trying to execute the main function

int main()
{
    Point pt1(3);
    pt1.print();
    std::cout << pt1[0] << std::endl;
    pt1.~Point();
}

I get a runtime error stating free(): double free detected in tcache 2. When I run the code through valgrind, It seems like the pointer values is delted twice (total heap usage: 3 allocs, 4 frees,...), which does not make any sense for me.

It's been a while since I wrote some c++ for the last time, so I have no clue what I am missing/skrewing up here and would appreciaty any help on this.

Thanks.

  • 6
    You shouldn't call the destructor manually. `pt1` has automatic storage duration so it will be destroyed automatically when it goes out of scope, which calls the destructor. By calling it yourself you are causing it to actually run twice, which isn't allowed. It's extremely rare to have to call the destructor explicitly like a function. – François Andrieux Oct 05 '21 at 19:12
  • Which C++ textbook offers an example of using a destructor, explicitly, like this? This looks like a typo in the textbook, that should be corrected. – Sam Varshavchik Oct 05 '21 at 19:16
  • @FrançoisAndrieux that should be posted as an answer – Remy Lebeau Oct 05 '21 at 19:19
  • @RemyLebeau Still looking for a duplicate. Edit : I think I found a good duplicate. – François Andrieux Oct 05 '21 at 19:20
  • Non- duplicate, but good reading: [Is calling destructor manually always a sign of bad design?](https://stackoverflow.com/questions/14187006/is-calling-destructor-manually-always-a-sign-of-bad-design) – user4581301 Oct 05 '21 at 19:21

0 Answers0