I've written a binary tree-like structure, but I've been getting stack-overflow errors in some of my stress tests. I've reduced the error-causing code down to the following: struct Node { index: usize, right: Option>, }
struct BoxedTree {
root: Option<Box<Node>>,
}
fn build_degenerate() {
let mut t = BoxedTree {
root: Some(Box::new(Node {
index: 0,
right: None,
})),
};
let mut n = t.root.as_mut().unwrap();
for i in 1..50000 {
let cur = n;
let p = &mut cur.right;
*p = Some(Box::new(Node {
index: i,
right: None,
}));
n = p.as_mut().unwrap();
}
println!("{}", n.index);
}
fn main() {
build_degenerate();
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn mytest() {
build_degenerate();
}
}
Running cargo test
gives me:
running 1 test
thread 'tests::mytest' has overflowed its stack
fatal runtime error: stack overflow
error: process didn't exit successfully: ...
I don't understand how this code could be causing a stack overflow, as all data seems to be allocated on the heap, and there is no recursion.
Even stranger, this code causes an overflow when I run cargo test
, but not when I run cargo run
, even though mytest
and main
call the same code.
What's going wrong here?