Question

I have a linked list defined by a structure

struct node {
    std::string elem;
    std::vector<node *> children;
};

Supposing that it was properly dynamically allocated, how do you free the heap afterwards? I am trying this:

void removeNodes(node* hElem) {
   for (node *hElemChildren: hElem->children)
       removeNodes(hElemChildren);
   delete hElem;
}

But I'm afraid that in this process I lose memory that was dynamically allocated to std::string and std::vector. Can someone please let me know if there is a memory leak here? Thanks!

Was it helpful?

Solution

There is no memory-leak here. When you call delete, destructor of this element will be called, that will call destructor for std::string and then for std::vector.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top