ECS 36A Lecture Notes - Lecture 18: Substructural Type System, C Dynamic Memory Allocation, Impi

138 views4 pages
28 Nov 2018
School
Course
Professor
ECS 36A - Lecture 18 - Ownership, Borrowing, and Lifetime
Void drop(char *p) { #example in C++
Free (p);
}
int main(){
char *p = malloc(...)
drop(p); #this would cause an error, because p is out of scope
*p =*a,
drop(p); #another error
}
Go & Rust are memory safe: Go(can’t free memory), Rust (stack linear type system)
Char *f(){ # each “scope” lives on a stack
char ch; # will go out of scope
return &ch, #&ch will get that address/value and return it
}
Int main(){
char *p = f(); #uses that return value of f()
*p = ‘a’;
}
People have tried to detect all security vulnerabilities, it’s not possible -- to check if a
program has a double free or used alpha free can’t be done precisely for every program
Rust linear type system-- operates through Ownership
- If you wish to share a value you must borrow it, but each variable can only have one
value
Ex:
struct Foo(i32);
let x = Foo(1);
let y = x; #this moves ownership from x to y
print(“{ }”, x}; #even though x EXISTS, it no longer owns a value -- x is inaccessible so error
struct Foo(i32);
let x = Foo(1);
let y = &x; #y BORROWS the value of x, X owns it
print( “{ }”, x); #this is legal
If you change the value of x, does the value of y change?
struct Foo(i32);
let x = Foo(1);
let y = &x;
Unlock document

This preview shows page 1 of the document.
Unlock all 4 pages and 3 million more documents.

Already have an account? Log in

Get OneClass Notes+

Unlimited access to class notes and textbook notes.

YearlyBest Value
75% OFF
$8 USD/m
Monthly
$30 USD/m
You will be charged $96 USD upfront and auto renewed at the end of each cycle. You may cancel anytime under Payment Settings. For more information, see our Terms and Privacy.
Payments are encrypted using 256-bit SSL. Powered by Stripe.