Skip to content

Use After Free in safe code using Vec and HashMap #19537

Closed
@Gankra

Description

@Gankra
use std::collections::HashMap;

#[deriving(Show)]
struct Foo<'a> {
    buf: Vec<String>,
    map: HashMap<uint, &'a str>
}

impl<'a> Foo<'a> {
    fn new() -> Foo<'a> {
        Foo { buf: Vec::new(), map: HashMap::new() }
    }
    fn insert(&'a mut self, s: String) {
        self.buf.push(s);
        match self.buf.last() {
            None => panic!(""),
            Some(x) => { self.map.insert(x.len(), x.as_slice()); }
        }
    }
    fn do_bad_stuff(&mut self) {
        self.buf.clear();
        self.buf.push("test".into_string());
    }
}
fn main() {
    let mut foo = Foo::new();
    foo.insert("bad".into_string());
    foo.insert("stuff".into_string());
    println!("{}", foo);
    foo.do_bad_stuff();
    println!("{}", foo);
}

Output:

Foo { buf: [bad, stuff], map: {5: stuff, 3: bad} }
Foo { buf: [test], map: {5: stuff, 3: tes} }

via

CC @nikomatsakis

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions