I have a function that adds weighted binary tree leafs or complex trees ( that have a right & left side ) to a vector.
I'm adding the new binary tree to the vector depending on it's weight ( since the vector contains weighted binary trees).
The problem is that whenever the function scope ends the binary tree pointers gets deallocated for some reason.
I have declared a copy constructor, = operator, constructor, move constructor...
But still it didn't work out. It always deallocates nodes more than once just because it's leaving the scope of the function.
Here is the destructor:
~WeightedBinaryTree() {
if (is_complex()){
std::pair<WeightedBinaryTree*, WeightedBinaryTree*> pair = std::get<std::pair<WeightedBinaryTree*, WeightedBinaryTree*>>(m_content); // m_content contains the binary trees.
delete pair.first; // left subtree
delete pair.second; // right subtree
}
}
Here is the code that is breaking the execution:
void insert_in_isorted(std::vector<D>& v, const D data){
std::cout << "Into insert_in_isorted..." << std::endl;
auto it = std::lower_bound(v.begin(), v.end(), data,
[](const D& a, const D& b) {
return a.get_weight() > b.get_weight();
});
std::cout << "Comparaison done..." << std::endl;
v.insert(it, data);
std::cout << "Inserted complex tree : " << data.get_weight() << std::endl;
} // Right on leaving the function const D data which represents the binary tree would get destroyed with it's children.
// In my case I have many binary trees in the vector that I'd like to merge into one single big tree.
// exp: [w_b_t(6,'e'),w_b_t(4,'e'),w_b_t(2,'e'),w_b_t(2,'a')] I would end up with [6,4,2,2] > [6,4,4] > [6,8] > [14]
Error:
double free or corruption (out).
Abandon (Core dumped)