Memory Safety in Rust

Will Crichton

memory safety in c?

// Use after free (heap)
int *a = malloc(sizeof(int));
free(a);
*a = 0;

// Use after free (stack)
int c = 0;
return &c;

// Double free
int *b = malloc(sizeof(int));
free(b);
free(b);



Memory safety in Rust?

fn foo<'a>() -> &'a i32 {
  &0
}

/*
test.rs:2:6: 2:7 error: borrowed value does not live long enough                                                                                                                                           
test.rs:2     &0                                                                                                                                                                                           
               ^                                                                                                                                                                                           
test.rs:1:25: 3:2 note: reference must be valid for the lifetime 'a as defined on the block at 1:24...                                                                                                     
test.rs:1 fn foo<'a>() -> &'a i32 {                                                                                                                                                                        
test.rs:2     &0                                                                                                                                                                                           
test.rs:3 }                                                                                                                                                                                                
test.rs:1:25: 3:2 note: ...but borrowed value is only valid for the block at 1:24                                                                                                                          
test.rs:1 fn foo<'a>() -> &'a i32 {                                                                                                                                                                        
test.rs:2     &0                                                                                                                                                                                           
test.rs:3 } 
*/
Made with Slides.com