So I am having to do this exercise for a course in Udemy and I finished it. But running in on my own machine in GDB I get the error above in the title. I tried checking the values of the pointers for the points prior and after destruction and the values of start behaved strangely on the destructor both of line and copy(both in the scope of main) On the first call to a destructor I couldn't access the values( it prints normally tho) for start and after destruction start->x was zero ( expected) but at the second destructor the value for start->x that was supposed to be three was zero too. But nothing in my code tells me (it might tell someone else) it's supposed to do that. I just can't figure it out
struct Point
{
int x{ 0 }, y{ 0 };
Point(){}
Point(const int x, const int y) : x{x}, y{y} {}
};
struct Line
{
Point *start, *end;
Line(Point* const start, Point* const end)
: start(start), end(end)
{
}
Line()
{
}
~Line()
{
delete start;
delete end;
}
Line& deep_copy() const
{
Point *cstart=new Point;
Point *cend=new Point;
(*cstart)=*start;
(*cend)=*end;
static Line copy{cstart, cend};
return copy;
}
};
#include <iostream>
using namespace std;
int main (){
Point *start= new Point(1,2);
Point *end = new Point(3,4);
Line line{start, end}, copy;
cout << line.start->x <<endl<< line.start->y <<endl<< line.end->x <<endl<< line.end->y <<endl;
copy = line.deep_copy();
cout << copy.start->x <<endl<< copy.start->y <<endl<< copy.end->x <<endl<< copy.end->y <<endl;
return 0;
}
When run, your program will create 3
Lineobjects:linein main (denoted hereafter bymain::line)copyin main (denoted hereafter bymain::copy)copyin deep_copy (denoted hereafter bydeep_copy::copy)Since
deep_copy::copyis a static object, it remains in memory after its creation till the end of the program run.Correspondingly, your program will have 3 destructor calls (pertaining to the
Linestruct objects). The first two will be formain::copyandmain::line. The third destructor call will be fordeep_copy::copyat the end of program run. Note that, the pointers (startandend) formain::copyanddeep_copy::copypoint to the same location, as the two objects are a copy of each other. Thus, during the third destructor call (meant fordeep_copy::copy), the memory pointed to bystartandendofdeep_copy::copyhas already been freed by the previous destructor call formain::copy.This leads to the runtime error:
free(): double free detected in tcache 2, as your program tries to free a memory location that has already been freed.