Search code examples
ruststack-overflow

Is it possible to predict stack overflow?


I have a Rust program that uses recursion. Sometimes it hits "stack overflow" runtime error. I want to prevent this from happening. Instead, I want to have something like this inside my recursive function:

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

Is it possible?


Solution

  • You can get an estimate for the remaining stack space from stacker::remaining_stack.

    But for detecting problems with recursion some more direct approach might be more appropriate:

    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
    }