Slazer
Slazer

Reputation: 4990

Segmentation fault (core dumped) using async in C++11

I created a function to convert an existing tree object to a string. Format of the string is

parent ( child1 ) ( child2 ( childOfChild2 ) )

The program outputs the string correctly, does some other work, but at the and crashes with

Segmentation fault (core dumped)

This is the function (getTree(this->root) outputs whole tree):

template <typename T>
string Tree<T>::getTree(const Node<T>& node) {
    if (node.isLeaf()){
        return to_string(node.value);
    }

    vector<future<string>> results; //each element represents a subtree connected to "node"
    for (auto child:node.children){
        results.push_back(move(async(&Tree<T>::getTree,this,ref(*child))));
    }

    string children("");
    for (auto& result:results){
        children+=string(" (") + result.get()+ string(") ");     //this creates Segmentation fault, but the output is correct
        //children+=string("");                                  //this does not create Segmentation fault
        //children+=string("foo");                               //this creates Segmentation fault
    }

    return to_string(node.value)+children;
}  

Some info about the variables:

vector<shared_ptr<Node>> children;

Please tell if you need more info. The full source is tree.cpp and tree.h.

Upvotes: 4

Views: 818

Answers (1)

cmeerw
cmeerw

Reputation: 7356

Your comparison function in the iterator doesn't work - you also need to cover the case where both containers are empty, i.e.

bool operator!= (const Iter& other) const {
    if (this->queueToIter.empty()&& other.queueToIter.empty()) return false;
    if (this->queueToIter.empty()&&! other.queueToIter.empty()) return true;
    if (!this->queueToIter.empty()&& other.queueToIter.empty()) return true;
    return (this->queueToIter.front())!=(other.queueToIter.front());
};

Upvotes: 1

Related Questions