简体   繁体   中英

C++ Function output changes after return

I am trying to get a vector of trees from a DFS traversal of a graph but the result changes after it is returned from the function.

This is the Tree class:

template <typename T>
class Tree
{
public:
    T v;    // value of current node
    // List of subtrees
    std::list<Tree<T>*> children;
    // Pointer to parent
    Tree<T> *parent;
    Tree(T v) {
        this->v = v;
    }
}

This is the relevant part of the function

    for (int i = 0; i < V; ++i)
        trees.push_back(Tree<T>(info[i]));

    int parent, node;
    std::vector<int> roots;
    for (int i = 0; i < V; ++i) {
        parent = parents[i];
        node = path[i];

        if (parent != -1) {
            trees[parent].children.push_back(&trees[node]);
            trees[node].parent = &trees[parent];
        }
        else {
            roots.push_back(node);
        }
    }
    for(int node_i : roots)
        res.push_back(trees[node]);
    return res;

and the variable declarations are these:

        template <typename T>
    std::vector<Tree<T>> DFSTree(std::vector<T> &info) {
    std::vector<Tree<T>> res;
    std::vector<int> path;
    std::vector<int> parents;
    std::vector<Tree<T>> trees;

The Tree within the resulting vectors' children don't have any children set. Sorry if this is a basic question but I couldn't find an answer anywhere. Thank you for the response

You have pointers in your Tree class. When you copy the tree nodes with res.push_back(trees[node]) , the child and parent pointers still point into trees , and not res . When the function returns, trees goes out of scope and its memory is freed, leaving the pointers in res pointing at deleted memory.

The fix is to rethink your design so you don't use pointers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM