Just a little silly Rust program that creates a recursive struct and triggers a stack overflow.
- Rust 100%
| Filename | Latest commit message | Latest commit date |
|---|---|---|
|
|
||
| src | ||
| .gitignore | ||
| Cargo.lock | ||
| Cargo.toml | ||
| README.md | ||
Ouroboros
The snake eating its tail. Funny little concept, so I made it in Rust using unsafe.
Relevant code:
let mut ouroboros = Snake {
tail: SnakeTail::Normal,
};
unsafe {
let ouroboros_ptr: *mut Snake = &mut ouroboros;
ouroboros_ptr.write(Snake {
tail: SnakeTail::Bitten(&ouroboros),
});
};
println!(
"The tail of the legendary creature, Ouroboros: {}",
ouroboros.tail
);
// Stack over-flow happens here
println!("All done!");
The main function is pretty simple overall, we make a Snake, and then set its Tail to be bitten by a reference to itself.
Usually, Rust wouldn't let you do this, since you cannot use a reference to a value while mutating that value.
I get around this by making a pointer instead, and writing to that in the unsafe block.
The output:
The tail of the legendary creature, Ouroboros: Wait, someone is biting it... Their tail: Wait, someone is biting it... Their tail: Wait, someone is biting it... Their tail: Wait, someone is biting it... Their tail: Wait, someone is biting it... Their tail: Wait, someone is biting it... Their tail: Wait, someone is biting it... Their tail: Wait, someone is biting it... Their tail: Wait, someone is biting it... Their tail: Wait, someone is biting it... Their tail: Wait, someone is biting it... Their tail: Wait, someone is biting it...
(that keeps going for a while)
thread 'main' (140712) has overflowed its stack
fatal runtime error: stack overflow, aborting
Quite funny, we love recursion
But... Why?
Because why not? I just made this because I thought it would be kind of funny to break Rust's borrowing rules a little and cause some chaos.