在构造一个大树</main>时,“thread'<main>'溢出了它的堆栈”

时间:2015-02-22 16:40:28

标签: rust

我实现了一个树形结构:

use std::collections::VecDeque;
use std::rc::{Rc, Weak};
use std::cell::RefCell;

struct A {
    children: Option<VecDeque<Rc<RefCell<A>>>>
}

// I got thread '<main>' has overflowed its stack
fn main(){
    let mut tree_stack: VecDeque<Rc<RefCell<A>>> = VecDeque::new();

    // when num is 1000, everything works
    for i in 0..100000 {
        tree_stack.push_back(Rc::new(RefCell::new(A {children: None})));
    }

    println!("{:?}", "reach here means we are not out of mem");
    loop {
        if tree_stack.len() == 1 {break;}

        let mut new_tree_node = Rc::new(RefCell::new(A {children: None}));
        let mut tree_node_children: VecDeque<Rc<RefCell<A>>> = VecDeque::new();

        // combine last two nodes to one new node
        match tree_stack.pop_back() {
            Some(x) => {
                tree_node_children.push_front(x);
            },
            None => {}
        } 
        match tree_stack.pop_back() {
            Some(x) => {
                tree_node_children.push_front(x);
            },
            None => {}
        } 

        new_tree_node.borrow_mut().children = Some(tree_node_children);
        tree_stack.push_back(new_tree_node);
    }
}

Playpen link

但它与

崩溃了
thread '<main>' has overflowed its stack

我该如何解决?

1 个答案:

答案 0 :(得分:6)

您遇到的问题是因为您有一个巨大的节点链表。删除该列表时,第一个元素首先尝试释放结构的所有成员。这意味着第二个元素的作用相同,依此类推,直到列表的结尾。这意味着您将拥有一个与列表中元素数量成比例的调用堆栈!

这是一个小小的复制品:

struct A {
    children: Option<Box<A>>
}

fn main() {
    let mut list = A { children: None };

    for _ in 0..1_000_000 {
        list = A { children: Some(Box::new(list)) };
    }
}

以下是解决问题的方法:

use std::mem;

impl Drop for A {
    fn drop(&mut self) {
        let mut children = mem::replace(&mut self.children, None);

        loop {
            children = match children {
                Some(mut n) => mem::replace(&mut n.children, None),
                None => break,
            }
        }
    }
}

此代码会覆盖默认的drop实现。它将children从节点中删除,将其替换为终端项(None)。然后它允许节点正常删除,但不会有递归调用。

代码很复杂,因为我们不能放弃自己,所以我们需要做一个两步舞,忽略第一项,吃掉所有孩子。