是否可以预测堆栈溢出?

yeg*_*256 2 stack-overflow rust

我有一个使用递归的 Rust 程序。有时它会遇到“堆栈溢出”运行时错误。我想阻止这种情况发生。相反,我想在我的递归函数中有这样的东西:

fn foo() -> u32 {
  if stack_is_almost_full() {
    panic!("Something is wrong with the recursion!");
  }
  // continue normally
}
Run Code Online (Sandbox Code Playgroud)

是否可以?

caf*_*e25 5

您可以从 获得剩余堆栈空间的估计值stacker::remaining_stack

但为了检测递归问题,一些更直接的方法可能更合适:

const MAX_DEPTH: usize = 1024;
#[inline(always)]
fn foo() -> u32 {
    foo_rec(0).expect("MAX_DEPTH reached while recursing")
}

fn foo_rec(depth: usize) -> Option<u32> {
    if depth > MAX_DEPTH {
        None
    }
    // do your work possibly recursing, finally return something
    if should_recurse() {
        foo_rec(depth + 1)
    } else {
        Some(42)
    }
}

fn should_recurse() -> bool {
    true // uh-oh
}
Run Code Online (Sandbox Code Playgroud)