Skip to content

Instantly share code, notes, and snippets.

@xarxziux
Created June 17, 2018 00:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xarxziux/e4ec3ec84ce3c16c81779a3bb4de4c50 to your computer and use it in GitHub Desktop.
Save xarxziux/e4ec3ec84ce3c16c81779a3bb4de4c50 to your computer and use it in GitHub Desktop.
Rust Memory Leak Demo
#[allow(dead_code)]
struct Entity {
level: u8,
health: u8
}
fn show_vector (next: &Option<Entity>) -> char {
match next {
&Some(_) => '0',
&None => '.'
}
}
fn main(){
// First define an "empty" element
let empty_entity: &Option<Entity> = &None;
// And now an "empty" vector
let mut entity_vec: Vec<&Option<Entity>> =vec![empty_entity; 10];
// Let's add some actual entities to the vector
entity_vec[1] = &Some (Entity {health: 83, level: 5});
entity_vec[3] = &Some (Entity {health: 81, level: 12});
entity_vec[7] = &Some (Entity {health: 97, level: 3});
// And now we can visualise the vector
for next in entity_vec.iter() {
print!("{}", show_vector (next));
}
println!("");
/*
* The main program logic goes here.
* Depending on the actions of the entites, they will either gain or lose health.
* If they reach maximum health, they spawn new entity but lose some health.
* If their health reaches zero they die.
*/
// Two of the entities have reached zero health so we kill them off.
entity_vec[1] = empty_entity;
entity_vec[7] = empty_entity;
// Now let's look at the vector
for next in entity_vec.iter() {
print!("{}", show_vector (next));
}
println!("");
// But where did the two entites go? Memory leak?
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment