Why does this overflow the stack?

I made a simple error and spent way too long trying to find what it was.

use std::ops::Index;

#[derive(Default)]
struct A([u32;5]);

fn crashes(a: A) -> u32 {
    a[1]
}

impl Index<usize> for A {
    type Output = u32;
    fn index(&self, row: usize) -> &Self::Output {
        debug_assert!((0..5).contains(&row));
        &self[row]
    }
}

fn main() {
    let s = crashes(A::default());
    println!("{s}");
}

In this example the compiler rightfully complains: "warning: field 0 is never read", but in a more complicated code the field might be used correctly in other pars and the source of the stack overflow might not be so apparent.

My question is why stack overflow and not segmentation fault?

Why would you not expect to get a stack overflow from infinite recursion?

2 Likes

You are totally right, im speechless
thanks :slight_smile: