Geek Answers Handbook
Thread '<main>' overflowed his stack in Rust
I got an error while trying this code that implements a simple linked list.
use std::rc::Rc;
use std::cell::RefCell;
struct Node {
a : Option<Rc<RefCell<Node>>>,
value: i32
}
impl Node {
fn new(value: i32) -> Rc<RefCell<Node>> {
let node = Node {
a: None,
value: value
};
Rc::new(RefCell::new(node))
}
}
fn main() {
let first = Node::new(0);
let mut t = first.clone();
for i in 1 .. 10_000
{
if t.borrow().a.is_none() {
t.borrow_mut().a = Some(Node::new(i));
}
if t.borrow().a.is_some() {
t = t.borrow().a.as_ref().unwrap().clone();
}
}
println!("Done!");
}
Why is this happening? Does this mean that Rust is not as secure as it is positioned?
UPD: If I add this method, the program will not work.
impl Drop for Node {
fn drop(&mut self) {
let mut children = mem::replace(&mut self.a, None);
loop {
children = match children {
Some(mut n) => mem::replace(&mut n.borrow_mut().a, None),
None => break,
}
}
}
}
But I'm not sure if this is the right decision.
+4
1 answer
Does this mean that Rust is not as secure as it is positioned?
Rust is protected only from certain types of failures; in particular, memory corruptions, which are described here: http://doc.rust-lang.org/reference.html#behavior-considered-undefined
, , , . , http://doc.rust-lang.org/reference.html#behavior-considered-undefined.
TL;DR; . , .
, , , , .
, , , ( - ).
.
:
fn main() {
let foo:&mut [i8] = &mut [1i8; 1024 * 1024];
}
( rustc, )
, Box:: new() ...
use std::rc::Rc;
use std::cell::RefCell;
#[derive(Debug)]
struct Node {
a : Option<Box<Rc<RefCell<Node>>>>,
value: i32
}
impl Node {
fn new(value: i32) -> Box<Rc<RefCell<Node>>> {
let node = Node {
a: None,
value: value
};
Box::new(Rc::new(RefCell::new(node)))
}
}
fn main() {
let first = Node::new(0);
let mut t = first.clone();
for i in 1 .. 10000
{
if t.borrow().a.is_none() {
t.borrow_mut().a = Some(Node::new(i));
}
if t.borrow().a.is_some() {
let c:Box<Rc<RefCell<Node>>>;
{ c = t.borrow().a.as_ref().unwrap().clone(); }
t = c;
println!("{:?}", t);
}
}
println!("Done!");
}
... . , , , , - , .
+4
All Articles