Thread has overflowed its stack

Hello there! I'm new to Rust and now started to solve "100 exercise to learn Rust"(GitHub - mainmatter/100-exercises-to-learn-rust: A self-paced course to learn Rust, one exercise at a time. · GitHub)

So there is the code:


fn factorial(n: u32) -> u32 {
    if n < 2 {
        1
    } else {
        n * factorial(n) - 1
    }
}

#[cfg(test)]
mod tests {
    use crate::factorial;
    
    #[test]
    fn first() {
        assert_eq!(factorial(0), 1);
    }
    
    #[test]
    fn second() {
        assert_eq!(factorial(1), 1);
    }
    
    #[test]
    fn third() {
        assert_eq!(factorial(2), 2);
    }
    
    #[test]
    fn fifth() {
        assert_eq!(factorial(5), 120);
    }
}

When I try to run ''cargo test" I have this message:

running 4 tests
test tests::first ... ok

thread 'tests::second' (308539) has overflowed its stack
fatal runtime error: stack overflow, aborting
error: test failed, to rerun pass `--lib`

Caused by:
  process didn't exit successfully: `/home/.../Rust/100exercises/2/factorial/target/debug/deps/factorial-23c7f241ea6c1944` (signal: 6, SIGABRT: process abort signal)

Does anybody know why is it don't exit successfully?

Because from factorial(n) you invoke factorial(n) once again.

Should your - 1 be inside the parenthesis when you are recursing?

(Edit: sorry, meant to quote OP)

Ohh I saw it now :man_facepalming:
it must be factorial(n-1)

Yes exactly. Maybe I'm just tired. Thanks mate!

You exhausted the stack memory size limit (stack overflow). Because the function keep calling itself in very many loopings, until it uses all the stack memory size

In linux you can check the stack size limit with

ulimit -s

Usually it is 8 MB

You can increase the stack size manually

But better to change the recursive algorithm to better algorithm