SlideShare a Scribd company logo
1 of 42
What the &~#@<!?
(Pointers in Rust)

Jodhpur, India (Dec 2011)
Plan for Today
Recap:
Explicit vs. Automatic Memory Management
More Advanced Managed Memory
Systematic, Explicit Memory Management
Last 15 minutes: Forming Teams for PS3

1
Memory Management Options
Unmanaged (Explicit)
C, C++
Up to programmer to free
objects

Managed (Automatic)
Java, C#, Go, Python, Scheme
Objects are automatically
reclaimed

2
Garbage Collection
Mark and Sweep
Compacting
Generational

Go
3
(Advanced “comic
book” version of GC)
4
5
Mark-and-sweep

about:config / javascript.options.mem.gc_incremental

6
Reference Counting
Each object keeps track of the number of
references to it:
if the reference count reaches 0, the object is
garbage
This is the most “incremental” GC can get!
7
Counting References
{
T x = new T ();
…
y = x;
…
}
8
static int
app1(PyListObject *self, PyObject *v)
{
Py_ssize_t n = PyList_GET_SIZE(self);
assert (v != NULL);
if (n == INT_MAX) {
PyErr_SetString(PyExc_OverflowError,
"cannot add more objects to list");
return -1;
}
if (list_resize(self, n+1) == -1)
return -1;
Py_INCREF(v);
PyList_SET_ITEM(self, n, v);
return 0;
}

Python’s list append implementation

#define _Py_NewReference(op) ( 
(op)->ob_refcnt = 1)
#define Py_INCREF(op) ( 
(op)->ob_refcnt++)
#define Py_DECREF(op) 
if (--(op)->ob_refcnt != 0) 
_Py_CHECK_REFCNT(op) 
else 
_Py_Dealloc((PyObject *)(op))
9
Is Reference Counting Enough?

10
Is Reference Counting Enough?
{
BigObject a = new BigObject();
BigObject b = new BigObject();
a.friend = b;
b.friend = a;

}

11
Memory Management Options
Unmanaged (Explicit)
C, C++
Up to programmer to free
objects

Managed (Automatic)
Java, C#, Go, Python, Scheme
Objects are automatically
reclaimed

Is bounds checking orthogonal to memory management?
12
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv) {
char *s = (char *) malloc (1024);
char *t = s - 12;
strcpy(s, "Hello!");
s = NULL;

printf("Reaching s: %sn", t + 12);
long int x = (long int) t + 12;
printf("Reaching s: %sn", (char *) x);
return 0;
}

13
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv) {
char *s = (char *) malloc (1024);
char *t = s - 12;
strcpy(s, "Hello!");
s = NULL;

gash> gcc -Wall managed.c
gash>./a.out
Reaching s: Hello!
Reaching s: Hello!

printf("Reaching s: %sn", t + 12);
long int x = (long int) t + 12;
printf("Reaching s: %sn", (char *) x);
return 0;
}

14
PLDI 1996

15
another paper from that conference…
PLDI 1996

16
Complaints about my earlier tool:

comp.os.linux post, August 1994
17
“Willy-Nilly” Memory Management

Systematic Memory Management
18
Static Detection of
Dynamic Memory
Errors, David Evans,
PLDI May 1996
19
20
Note: these are “compile-time” errors (just produced by a separate tool).
21
A box is a reference to a heap allocation holding another value.
There are two kinds of boxes: managed boxes and owned boxes.
An owned box type or value is constructed by the prefix tilde sigil ~.
Rust Manual, Section 9.1.4

let mut gname : ~str = ~"annotations";

22
Moving Pointers
Lose reference of
owned pointer
after it is
transferred.

fn main() {
let owned = ~"All mine!";
println!("Whose is it? {:s}", owned);
let stolen = owned;
println!("Whose is it? {:s}", stolen);
}

23
fn main() {
let owned = ~"All mine!";
let stolen = owned;
println!("Whose is it? {:s}", owned);
} owned.rs:4:34: 4:39 error: use of moved value: `owned`
owned.rs:4 println!("Whose is it? {:s}", owned);
^~~~~
note: in expansion of format_args!
<std-macros>:195:27: 195:81 note: expansion site
<std-macros>:194:5: 196:6 note: in expansion of println!
owned.rs:4:4: 4:41 note: expansion site
owned.rs:3:8: 3:14 note: `owned` moved here because it has type `~str`, which is moved by
default (use `ref` to override)
owned.rs:3 let stolen = owned;
^~~~~~
error: aborting due to previous error
24
fn main() {
let owned = ~"All mine!";
let ref stolen = owned;
println!("Whose is it? {:s}", owned);
println!("Whose is it? {:s}", *stolen);
}
fn main() {
let owned: ~str = ~"Mine, all mine!";
let ref stolen : ~str;
stolen = &owned;

println!("Whose is it? {:s}", *stolen);
}
25
fn main() {
let owned: ~str = ~"Mine, all mine!";
let ref stolen : ~str;
stolen = &owned;
fn main() {
let ref stolen : ~str;
println!("Whose is it? {:s}", *stolen);
}
{
let mine: ~str = ~"Mine, all mine!";
stolen = &mine;
}
println!("Whose is it? {:s}", *stolen);
}

26
lifetimes.rs:6:16: 6:21 error: borrowed
value does not live long enough
lifetimes.rs:6
stolen = &mine;
^~~~~
lifetimes.rs:1:11: 10:2 note: reference
must be valid for the block at 1:10...
...
lifetimes.rs:4:4: 7:5 note: ...but
borrowed value is only valid for the
block at 4:3
…

fn main() {
let ref stolen : ~str;

{
let mine: ~str = ~”Mine!";
stolen = &mine;
}
...
}

See Kiet’s blog to understand more about how the Rust compiler does this:
http://ktt3ja.github.io/blog/2014/02/10/understanding-rusts-lifetime-inference/
27
Object’s Lifetime

We cannot borrow an
object for longer than
that object may live!

Length of “loan”

Borrow Lifetimes

28
fn bigger(s1: &str, s2: &str) -> &str {
if s1.len() > s2.len() { s1 } else { s2 }
}
fn main() {
let s: ~str = ~"Mine!";
let t: ~str = ~"Yours!";
println!("Whose is it? {:s}", bigger(s, t));
}

29
borrow.rs:2:5: 2:46 error: cannot infer an appropriate lifetime due to conflicting requirements
borrow.rs:2 if s1.len() > s2.len() { s1 } else { s2 }
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
borrow.rs:1:39: 3:2 note: first, the lifetime cannot outlive the anonymous lifetime #2 defined on the block at 1:38...
borrow.rs:1 fn bigger(s1: &str, s2: &str) -> &str {
fn bigger(s1: &str, s2: &str) -> &str {
borrow.rs:2 if s1.len() > s2.len() { s1 } else { s2 }
borrow.rs:3 }
if s1.len() > s2.len() { s1 } else { s2 }
borrow.rs:2:5: 2:46 note: ...so that if and else have compatible types (expected `&str` but found `&str`)
}
borrow.rs:2 if s1.len() > s2.len() { s1 } else { s2 }
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
borrow.rs:1:39: 3:2 note: but, the lifetime must be valid for the anonymous lifetime #3 defined on the block at
1:38...
borrow.rs:1 fn bigger(s1: &str, s2: &str) -> &str {
borrow.rs:2 if s1.len() > s2.len() { s1 } else { s2 }
borrow.rs:3 }
borrow.rs:2:5: 2:46 note: ...so that types are compatible (expected `&str` but found `&str`)
borrow.rs:2 if s1.len() > s2.len() { s1 } else { s2 }
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
error: aborting due to previous error
30
fn bigger<'a>(s1: &'a str, s2: &'a str) -> &'a str {
if s1.len() > s2.len() { s1 } else { s2 }
}

Lifetime parameter: Rust infers minimum
lifetime of all uses, and bind it to parameter
31
fn bigger<'a>(s1: &'a str, s2: &'a str) -> &'a str {
if s1.len() > s2.len() { s1 } else { s2 }
}
fn main() {
let s: ~str = ~"Mine!";
let r: &str;
{

let t: ~str = ~"Yours!";
r = bigger(s, t);
}

println!("Whose is bigger? {:s}", r);
}
32
fn bigger<'a>(s1: &'a str, s2: &'a str) -> &'a str {
if s1.len() > s2.len() { s1 } else { s2 }
}
fn main() {
let s: ~str = ~"Mine!";
let r: &str;
{
let t: ~str = ~"Yours!";
r = bigger(s, t);

}

borrow2.rs:11:21: 11:22 error: borrowed value does not live long enough
borrow2.rs:11
r = bigger(s, t);
println!("Whose is bigger? {:s}", r); ^
borrow2.rs:5:11: 15:2 note: reference must be valid for the block at 5:10...
}
borrow2.rs:9:4: 12:5 note: ...but borrowed value is only valid for the block at
9:3
33
Can we do this in Rust?
34
fn set_name(gname:
pname: ~str) {
*gname = pname;
}

,

35
fn set_name(gname : &mut ~str, pname : ~str) {
*gname = pname;
}

fn main() {
let mut gname : ~str = ~"annotations";
println!("gname = {:s}", gname);
set_name(&mut gname, ~"frees");
println!("gname = {:s}", gname);
}
36
fn set_name(gname : &mut ~str, pname : ~str) {
*gname = pname;
}

Why doesn’t Rust complain about the missing free?
37
Frees?
Where we are going,
we don’t need
frees!

38
Memory Management Options
Unmanaged (Explicit)
C, C++
Up to programmer to free
objects

Managed (Automatic)
Java, C#, Go, Python, Scheme
Objects are automatically
reclaimed

Which is Rust?
39
Problem Set 3

40
Forming Teams for PS3
For this problem set, you are required to work in a team of two or three
people (except in cases where you were notified based on your PS2 teamwork
that you should work alone for PS3, or where you make your own successful
argument before February 19 that it is better for you to work alone).
Your team may not be the same as your team for PS2, so you should either (1)
find a new partner to work with for PS3, or
(2) if you want to work with your PS2 partner again you must find one other
person to join your team.
If you do not end up on a well-formed team by the end of class on 18 February,
you should contact me right away.
41

More Related Content

What's hot

Introduction to Rust language programming
Introduction to Rust language programmingIntroduction to Rust language programming
Introduction to Rust language programmingRodolfo Finochietti
 
An introduction to Rust: the modern programming language to develop safe and ...
An introduction to Rust: the modern programming language to develop safe and ...An introduction to Rust: the modern programming language to develop safe and ...
An introduction to Rust: the modern programming language to develop safe and ...Claudio Capobianco
 
The Rust Programming Language: an Overview
The Rust Programming Language: an OverviewThe Rust Programming Language: an Overview
The Rust Programming Language: an OverviewRoberto Casadei
 
Evgeniy Muralev, Mark Vince, Working with the compiler, not against it
Evgeniy Muralev, Mark Vince, Working with the compiler, not against itEvgeniy Muralev, Mark Vince, Working with the compiler, not against it
Evgeniy Muralev, Mark Vince, Working with the compiler, not against itSergey Platonov
 
Linux seccomp(2) vs OpenBSD pledge(2)
Linux seccomp(2) vs OpenBSD pledge(2)Linux seccomp(2) vs OpenBSD pledge(2)
Linux seccomp(2) vs OpenBSD pledge(2)Giovanni Bechis
 
Code GPU with CUDA - Applying optimization techniques
Code GPU with CUDA - Applying optimization techniquesCode GPU with CUDA - Applying optimization techniques
Code GPU with CUDA - Applying optimization techniquesMarina Kolpakova
 
grsecurity and PaX
grsecurity and PaXgrsecurity and PaX
grsecurity and PaXKernel TLV
 
Gor Nishanov, C++ Coroutines – a negative overhead abstraction
Gor Nishanov,  C++ Coroutines – a negative overhead abstractionGor Nishanov,  C++ Coroutines – a negative overhead abstraction
Gor Nishanov, C++ Coroutines – a negative overhead abstractionSergey Platonov
 
Specializing the Data Path - Hooking into the Linux Network Stack
Specializing the Data Path - Hooking into the Linux Network StackSpecializing the Data Path - Hooking into the Linux Network Stack
Specializing the Data Path - Hooking into the Linux Network StackKernel TLV
 
Zn task - defcon russia 20
Zn task  - defcon russia 20Zn task  - defcon russia 20
Zn task - defcon russia 20DefconRussia
 
pa-pe-pi-po-pure Python Text Processing
pa-pe-pi-po-pure Python Text Processingpa-pe-pi-po-pure Python Text Processing
pa-pe-pi-po-pure Python Text ProcessingRodrigo Senra
 
How to make a large C++-code base manageable
How to make a large C++-code base manageableHow to make a large C++-code base manageable
How to make a large C++-code base manageablecorehard_by
 
Rust Intro @ Roma Rust meetup
Rust Intro @ Roma Rust meetup Rust Intro @ Roma Rust meetup
Rust Intro @ Roma Rust meetup Claudio Capobianco
 
Антон Бикинеев, Reflection in C++Next
Антон Бикинеев,  Reflection in C++NextАнтон Бикинеев,  Reflection in C++Next
Антон Бикинеев, Reflection in C++NextSergey Platonov
 
Pepe Vila - Cache and Syphilis [rooted2019]
Pepe Vila - Cache and Syphilis [rooted2019]Pepe Vila - Cache and Syphilis [rooted2019]
Pepe Vila - Cache and Syphilis [rooted2019]RootedCON
 

What's hot (20)

Introduction to Rust language programming
Introduction to Rust language programmingIntroduction to Rust language programming
Introduction to Rust language programming
 
An introduction to Rust: the modern programming language to develop safe and ...
An introduction to Rust: the modern programming language to develop safe and ...An introduction to Rust: the modern programming language to develop safe and ...
An introduction to Rust: the modern programming language to develop safe and ...
 
The Rust Programming Language: an Overview
The Rust Programming Language: an OverviewThe Rust Programming Language: an Overview
The Rust Programming Language: an Overview
 
Rust-lang
Rust-langRust-lang
Rust-lang
 
Introduction to Rust
Introduction to RustIntroduction to Rust
Introduction to Rust
 
Evgeniy Muralev, Mark Vince, Working with the compiler, not against it
Evgeniy Muralev, Mark Vince, Working with the compiler, not against itEvgeniy Muralev, Mark Vince, Working with the compiler, not against it
Evgeniy Muralev, Mark Vince, Working with the compiler, not against it
 
Pledge in OpenBSD
Pledge in OpenBSDPledge in OpenBSD
Pledge in OpenBSD
 
Linux seccomp(2) vs OpenBSD pledge(2)
Linux seccomp(2) vs OpenBSD pledge(2)Linux seccomp(2) vs OpenBSD pledge(2)
Linux seccomp(2) vs OpenBSD pledge(2)
 
Code GPU with CUDA - Applying optimization techniques
Code GPU with CUDA - Applying optimization techniquesCode GPU with CUDA - Applying optimization techniques
Code GPU with CUDA - Applying optimization techniques
 
grsecurity and PaX
grsecurity and PaXgrsecurity and PaX
grsecurity and PaX
 
Gor Nishanov, C++ Coroutines – a negative overhead abstraction
Gor Nishanov,  C++ Coroutines – a negative overhead abstractionGor Nishanov,  C++ Coroutines – a negative overhead abstraction
Gor Nishanov, C++ Coroutines – a negative overhead abstraction
 
Specializing the Data Path - Hooking into the Linux Network Stack
Specializing the Data Path - Hooking into the Linux Network StackSpecializing the Data Path - Hooking into the Linux Network Stack
Specializing the Data Path - Hooking into the Linux Network Stack
 
Rust言語紹介
Rust言語紹介Rust言語紹介
Rust言語紹介
 
Zn task - defcon russia 20
Zn task  - defcon russia 20Zn task  - defcon russia 20
Zn task - defcon russia 20
 
pa-pe-pi-po-pure Python Text Processing
pa-pe-pi-po-pure Python Text Processingpa-pe-pi-po-pure Python Text Processing
pa-pe-pi-po-pure Python Text Processing
 
How to make a large C++-code base manageable
How to make a large C++-code base manageableHow to make a large C++-code base manageable
How to make a large C++-code base manageable
 
Rust Intro @ Roma Rust meetup
Rust Intro @ Roma Rust meetup Rust Intro @ Roma Rust meetup
Rust Intro @ Roma Rust meetup
 
Антон Бикинеев, Reflection in C++Next
Антон Бикинеев,  Reflection in C++NextАнтон Бикинеев,  Reflection in C++Next
Антон Бикинеев, Reflection in C++Next
 
Full Stack Clojure
Full Stack ClojureFull Stack Clojure
Full Stack Clojure
 
Pepe Vila - Cache and Syphilis [rooted2019]
Pepe Vila - Cache and Syphilis [rooted2019]Pepe Vila - Cache and Syphilis [rooted2019]
Pepe Vila - Cache and Syphilis [rooted2019]
 

Viewers also liked

Invent the Future (Operating Systems in 2029)
Invent the Future (Operating Systems in 2029)Invent the Future (Operating Systems in 2029)
Invent the Future (Operating Systems in 2029)David Evans
 
Making a Process (Virtualizing Memory)
Making a Process (Virtualizing Memory)Making a Process (Virtualizing Memory)
Making a Process (Virtualizing Memory)David Evans
 
Smarter Scheduling (Priorities, Preemptive Priority Scheduling, Lottery and S...
Smarter Scheduling (Priorities, Preemptive Priority Scheduling, Lottery and S...Smarter Scheduling (Priorities, Preemptive Priority Scheduling, Lottery and S...
Smarter Scheduling (Priorities, Preemptive Priority Scheduling, Lottery and S...David Evans
 
Once Upon a Process
Once Upon a ProcessOnce Upon a Process
Once Upon a ProcessDavid Evans
 
Segmentation Faults, Page Faults, Processes, Threads, and Tasks
Segmentation Faults, Page Faults, Processes, Threads, and TasksSegmentation Faults, Page Faults, Processes, Threads, and Tasks
Segmentation Faults, Page Faults, Processes, Threads, and TasksDavid Evans
 
Class 1: What is an Operating System?
Class 1: What is an Operating System?Class 1: What is an Operating System?
Class 1: What is an Operating System?David Evans
 
Microkernels and Beyond
Microkernels and BeyondMicrokernels and Beyond
Microkernels and BeyondDavid Evans
 
Scheduling in Linux and Web Servers
Scheduling in Linux and Web ServersScheduling in Linux and Web Servers
Scheduling in Linux and Web ServersDavid Evans
 
Gash Has No Privileges
Gash Has No PrivilegesGash Has No Privileges
Gash Has No PrivilegesDavid Evans
 
Inventing the Future
Inventing the FutureInventing the Future
Inventing the FutureDavid Evans
 
Flash! (Modern File Systems)
Flash! (Modern File Systems)Flash! (Modern File Systems)
Flash! (Modern File Systems)David Evans
 
Zero to a Billion in 4.86 Years (A Whirlwind History of Operating Systems)
Zero to a Billion in 4.86 Years (A Whirlwind History of Operating Systems)Zero to a Billion in 4.86 Years (A Whirlwind History of Operating Systems)
Zero to a Billion in 4.86 Years (A Whirlwind History of Operating Systems)David Evans
 

Viewers also liked (15)

Invent the Future (Operating Systems in 2029)
Invent the Future (Operating Systems in 2029)Invent the Future (Operating Systems in 2029)
Invent the Future (Operating Systems in 2029)
 
Making a Process (Virtualizing Memory)
Making a Process (Virtualizing Memory)Making a Process (Virtualizing Memory)
Making a Process (Virtualizing Memory)
 
Smarter Scheduling (Priorities, Preemptive Priority Scheduling, Lottery and S...
Smarter Scheduling (Priorities, Preemptive Priority Scheduling, Lottery and S...Smarter Scheduling (Priorities, Preemptive Priority Scheduling, Lottery and S...
Smarter Scheduling (Priorities, Preemptive Priority Scheduling, Lottery and S...
 
The Internet
The InternetThe Internet
The Internet
 
Managing Memory
Managing MemoryManaging Memory
Managing Memory
 
Once Upon a Process
Once Upon a ProcessOnce Upon a Process
Once Upon a Process
 
Segmentation Faults, Page Faults, Processes, Threads, and Tasks
Segmentation Faults, Page Faults, Processes, Threads, and TasksSegmentation Faults, Page Faults, Processes, Threads, and Tasks
Segmentation Faults, Page Faults, Processes, Threads, and Tasks
 
Class 1: What is an Operating System?
Class 1: What is an Operating System?Class 1: What is an Operating System?
Class 1: What is an Operating System?
 
Microkernels and Beyond
Microkernels and BeyondMicrokernels and Beyond
Microkernels and Beyond
 
Scheduling in Linux and Web Servers
Scheduling in Linux and Web ServersScheduling in Linux and Web Servers
Scheduling in Linux and Web Servers
 
Gash Has No Privileges
Gash Has No PrivilegesGash Has No Privileges
Gash Has No Privileges
 
Storage
StorageStorage
Storage
 
Inventing the Future
Inventing the FutureInventing the Future
Inventing the Future
 
Flash! (Modern File Systems)
Flash! (Modern File Systems)Flash! (Modern File Systems)
Flash! (Modern File Systems)
 
Zero to a Billion in 4.86 Years (A Whirlwind History of Operating Systems)
Zero to a Billion in 4.86 Years (A Whirlwind History of Operating Systems)Zero to a Billion in 4.86 Years (A Whirlwind History of Operating Systems)
Zero to a Billion in 4.86 Years (A Whirlwind History of Operating Systems)
 

Similar to What the &~#@&lt;!? (Pointers in Rust)

Introduce to Rust-A Powerful System Language
Introduce to Rust-A Powerful System LanguageIntroduce to Rust-A Powerful System Language
Introduce to Rust-A Powerful System Language安齊 劉
 
Ownership System in Rust
Ownership System in RustOwnership System in Rust
Ownership System in RustChih-Hsuan Kuo
 
Basic C++ 11/14 for Python Programmers
Basic C++ 11/14 for Python ProgrammersBasic C++ 11/14 for Python Programmers
Basic C++ 11/14 for Python ProgrammersAppier
 
Basic c++ 11/14 for python programmers
Basic c++ 11/14 for python programmersBasic c++ 11/14 for python programmers
Basic c++ 11/14 for python programmersJen Yee Hong
 
Start Wrap Episode 11: A New Rope
Start Wrap Episode 11: A New RopeStart Wrap Episode 11: A New Rope
Start Wrap Episode 11: A New RopeYung-Yu Chen
 
Rust "Hot or Not" at Sioux
Rust "Hot or Not" at SiouxRust "Hot or Not" at Sioux
Rust "Hot or Not" at Siouxnikomatsakis
 
Rust: код может быть одновременно безопасным и быстрым, Степан Кольцов
Rust: код может быть одновременно безопасным и быстрым, Степан КольцовRust: код может быть одновременно безопасным и быстрым, Степан Кольцов
Rust: код может быть одновременно безопасным и быстрым, Степан КольцовYandex
 
Степан Кольцов — Rust — лучше, чем C++
Степан Кольцов — Rust — лучше, чем C++Степан Кольцов — Rust — лучше, чем C++
Степан Кольцов — Rust — лучше, чем C++Yandex
 
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...DevGAMM Conference
 
Short intro to the Rust language
Short intro to the Rust languageShort intro to the Rust language
Short intro to the Rust languageGines Espada
 
Rust: Reach Further
Rust: Reach FurtherRust: Reach Further
Rust: Reach Furthernikomatsakis
 
Giorgio zoppi cpp11concurrency
Giorgio zoppi cpp11concurrencyGiorgio zoppi cpp11concurrency
Giorgio zoppi cpp11concurrencyGiorgio Zoppi
 
Os Vanrossum
Os VanrossumOs Vanrossum
Os Vanrossumoscon2007
 
Rust Workshop - NITC FOSSMEET 2017
Rust Workshop - NITC FOSSMEET 2017 Rust Workshop - NITC FOSSMEET 2017
Rust Workshop - NITC FOSSMEET 2017 pramode_ce
 
Class 31: Deanonymizing
Class 31: DeanonymizingClass 31: Deanonymizing
Class 31: DeanonymizingDavid Evans
 
TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic LabsTypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic LabsAlfonso Peletier
 

Similar to What the &~#@&lt;!? (Pointers in Rust) (20)

Introduce to Rust-A Powerful System Language
Introduce to Rust-A Powerful System LanguageIntroduce to Rust-A Powerful System Language
Introduce to Rust-A Powerful System Language
 
Ownership System in Rust
Ownership System in RustOwnership System in Rust
Ownership System in Rust
 
Basic C++ 11/14 for Python Programmers
Basic C++ 11/14 for Python ProgrammersBasic C++ 11/14 for Python Programmers
Basic C++ 11/14 for Python Programmers
 
Basic c++ 11/14 for python programmers
Basic c++ 11/14 for python programmersBasic c++ 11/14 for python programmers
Basic c++ 11/14 for python programmers
 
Start Wrap Episode 11: A New Rope
Start Wrap Episode 11: A New RopeStart Wrap Episode 11: A New Rope
Start Wrap Episode 11: A New Rope
 
Rust "Hot or Not" at Sioux
Rust "Hot or Not" at SiouxRust "Hot or Not" at Sioux
Rust "Hot or Not" at Sioux
 
Rust: код может быть одновременно безопасным и быстрым, Степан Кольцов
Rust: код может быть одновременно безопасным и быстрым, Степан КольцовRust: код может быть одновременно безопасным и быстрым, Степан Кольцов
Rust: код может быть одновременно безопасным и быстрым, Степан Кольцов
 
Степан Кольцов — Rust — лучше, чем C++
Степан Кольцов — Rust — лучше, чем C++Степан Кольцов — Rust — лучше, чем C++
Степан Кольцов — Rust — лучше, чем C++
 
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
 
Short intro to the Rust language
Short intro to the Rust languageShort intro to the Rust language
Short intro to the Rust language
 
Rust vs C++
Rust vs C++Rust vs C++
Rust vs C++
 
Rustlabs Quick Start
Rustlabs Quick StartRustlabs Quick Start
Rustlabs Quick Start
 
Rust: Reach Further
Rust: Reach FurtherRust: Reach Further
Rust: Reach Further
 
Giorgio zoppi cpp11concurrency
Giorgio zoppi cpp11concurrencyGiorgio zoppi cpp11concurrency
Giorgio zoppi cpp11concurrency
 
The_Borrow_Checker.pdf
The_Borrow_Checker.pdfThe_Borrow_Checker.pdf
The_Borrow_Checker.pdf
 
Briefly Rust
Briefly RustBriefly Rust
Briefly Rust
 
Os Vanrossum
Os VanrossumOs Vanrossum
Os Vanrossum
 
Rust Workshop - NITC FOSSMEET 2017
Rust Workshop - NITC FOSSMEET 2017 Rust Workshop - NITC FOSSMEET 2017
Rust Workshop - NITC FOSSMEET 2017
 
Class 31: Deanonymizing
Class 31: DeanonymizingClass 31: Deanonymizing
Class 31: Deanonymizing
 
TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic LabsTypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
 

More from David Evans

Cryptocurrency Jeopardy!
Cryptocurrency Jeopardy!Cryptocurrency Jeopardy!
Cryptocurrency Jeopardy!David Evans
 
Trick or Treat?: Bitcoin for Non-Believers, Cryptocurrencies for Cypherpunks
Trick or Treat?: Bitcoin for Non-Believers, Cryptocurrencies for CypherpunksTrick or Treat?: Bitcoin for Non-Believers, Cryptocurrencies for Cypherpunks
Trick or Treat?: Bitcoin for Non-Believers, Cryptocurrencies for CypherpunksDavid Evans
 
Hidden Services, Zero Knowledge
Hidden Services, Zero KnowledgeHidden Services, Zero Knowledge
Hidden Services, Zero KnowledgeDavid Evans
 
Anonymity in Bitcoin
Anonymity in BitcoinAnonymity in Bitcoin
Anonymity in BitcoinDavid Evans
 
Midterm Confirmations
Midterm ConfirmationsMidterm Confirmations
Midterm ConfirmationsDavid Evans
 
Scripting Transactions
Scripting TransactionsScripting Transactions
Scripting TransactionsDavid Evans
 
How to Live in Paradise
How to Live in ParadiseHow to Live in Paradise
How to Live in ParadiseDavid Evans
 
Mining Economics
Mining EconomicsMining Economics
Mining EconomicsDavid Evans
 
Becoming More Paranoid
Becoming More ParanoidBecoming More Paranoid
Becoming More ParanoidDavid Evans
 
Asymmetric Key Signatures
Asymmetric Key SignaturesAsymmetric Key Signatures
Asymmetric Key SignaturesDavid Evans
 
Introduction to Cryptography
Introduction to CryptographyIntroduction to Cryptography
Introduction to CryptographyDavid Evans
 
Class 1: What is Money?
Class 1: What is Money?Class 1: What is Money?
Class 1: What is Money?David Evans
 
Multi-Party Computation for the Masses
Multi-Party Computation for the MassesMulti-Party Computation for the Masses
Multi-Party Computation for the MassesDavid Evans
 
Proof of Reserve
Proof of ReserveProof of Reserve
Proof of ReserveDavid Evans
 
Blooming Sidechains!
Blooming Sidechains!Blooming Sidechains!
Blooming Sidechains!David Evans
 
Useful Proofs of Work, Permacoin
Useful Proofs of Work, PermacoinUseful Proofs of Work, Permacoin
Useful Proofs of Work, PermacoinDavid Evans
 

More from David Evans (20)

Cryptocurrency Jeopardy!
Cryptocurrency Jeopardy!Cryptocurrency Jeopardy!
Cryptocurrency Jeopardy!
 
Trick or Treat?: Bitcoin for Non-Believers, Cryptocurrencies for Cypherpunks
Trick or Treat?: Bitcoin for Non-Believers, Cryptocurrencies for CypherpunksTrick or Treat?: Bitcoin for Non-Believers, Cryptocurrencies for Cypherpunks
Trick or Treat?: Bitcoin for Non-Believers, Cryptocurrencies for Cypherpunks
 
Hidden Services, Zero Knowledge
Hidden Services, Zero KnowledgeHidden Services, Zero Knowledge
Hidden Services, Zero Knowledge
 
Anonymity in Bitcoin
Anonymity in BitcoinAnonymity in Bitcoin
Anonymity in Bitcoin
 
Midterm Confirmations
Midterm ConfirmationsMidterm Confirmations
Midterm Confirmations
 
Scripting Transactions
Scripting TransactionsScripting Transactions
Scripting Transactions
 
How to Live in Paradise
How to Live in ParadiseHow to Live in Paradise
How to Live in Paradise
 
Bitcoin Script
Bitcoin ScriptBitcoin Script
Bitcoin Script
 
Mining Economics
Mining EconomicsMining Economics
Mining Economics
 
Mining
MiningMining
Mining
 
The Blockchain
The BlockchainThe Blockchain
The Blockchain
 
Becoming More Paranoid
Becoming More ParanoidBecoming More Paranoid
Becoming More Paranoid
 
Asymmetric Key Signatures
Asymmetric Key SignaturesAsymmetric Key Signatures
Asymmetric Key Signatures
 
Introduction to Cryptography
Introduction to CryptographyIntroduction to Cryptography
Introduction to Cryptography
 
Class 1: What is Money?
Class 1: What is Money?Class 1: What is Money?
Class 1: What is Money?
 
Multi-Party Computation for the Masses
Multi-Party Computation for the MassesMulti-Party Computation for the Masses
Multi-Party Computation for the Masses
 
Proof of Reserve
Proof of ReserveProof of Reserve
Proof of Reserve
 
Silk Road
Silk RoadSilk Road
Silk Road
 
Blooming Sidechains!
Blooming Sidechains!Blooming Sidechains!
Blooming Sidechains!
 
Useful Proofs of Work, Permacoin
Useful Proofs of Work, PermacoinUseful Proofs of Work, Permacoin
Useful Proofs of Work, Permacoin
 

Recently uploaded

Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)cama23
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptxiammrhaywood
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4JOYLYNSAMANIEGO
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...JojoEDelaCruz
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 

Recently uploaded (20)

Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 

What the &~#@&lt;!? (Pointers in Rust)

  • 1. What the &~#@<!? (Pointers in Rust) Jodhpur, India (Dec 2011)
  • 2. Plan for Today Recap: Explicit vs. Automatic Memory Management More Advanced Managed Memory Systematic, Explicit Memory Management Last 15 minutes: Forming Teams for PS3 1
  • 3. Memory Management Options Unmanaged (Explicit) C, C++ Up to programmer to free objects Managed (Automatic) Java, C#, Go, Python, Scheme Objects are automatically reclaimed 2
  • 4. Garbage Collection Mark and Sweep Compacting Generational Go 3
  • 6. 5
  • 8. Reference Counting Each object keeps track of the number of references to it: if the reference count reaches 0, the object is garbage This is the most “incremental” GC can get! 7
  • 9. Counting References { T x = new T (); … y = x; … } 8
  • 10. static int app1(PyListObject *self, PyObject *v) { Py_ssize_t n = PyList_GET_SIZE(self); assert (v != NULL); if (n == INT_MAX) { PyErr_SetString(PyExc_OverflowError, "cannot add more objects to list"); return -1; } if (list_resize(self, n+1) == -1) return -1; Py_INCREF(v); PyList_SET_ITEM(self, n, v); return 0; } Python’s list append implementation #define _Py_NewReference(op) ( (op)->ob_refcnt = 1) #define Py_INCREF(op) ( (op)->ob_refcnt++) #define Py_DECREF(op) if (--(op)->ob_refcnt != 0) _Py_CHECK_REFCNT(op) else _Py_Dealloc((PyObject *)(op)) 9
  • 11. Is Reference Counting Enough? 10
  • 12. Is Reference Counting Enough? { BigObject a = new BigObject(); BigObject b = new BigObject(); a.friend = b; b.friend = a; } 11
  • 13. Memory Management Options Unmanaged (Explicit) C, C++ Up to programmer to free objects Managed (Automatic) Java, C#, Go, Python, Scheme Objects are automatically reclaimed Is bounds checking orthogonal to memory management? 12
  • 14. #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char **argv) { char *s = (char *) malloc (1024); char *t = s - 12; strcpy(s, "Hello!"); s = NULL; printf("Reaching s: %sn", t + 12); long int x = (long int) t + 12; printf("Reaching s: %sn", (char *) x); return 0; } 13
  • 15. #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char **argv) { char *s = (char *) malloc (1024); char *t = s - 12; strcpy(s, "Hello!"); s = NULL; gash> gcc -Wall managed.c gash>./a.out Reaching s: Hello! Reaching s: Hello! printf("Reaching s: %sn", t + 12); long int x = (long int) t + 12; printf("Reaching s: %sn", (char *) x); return 0; } 14
  • 17. another paper from that conference… PLDI 1996 16
  • 18. Complaints about my earlier tool: comp.os.linux post, August 1994 17
  • 20. Static Detection of Dynamic Memory Errors, David Evans, PLDI May 1996 19
  • 21. 20
  • 22. Note: these are “compile-time” errors (just produced by a separate tool). 21
  • 23. A box is a reference to a heap allocation holding another value. There are two kinds of boxes: managed boxes and owned boxes. An owned box type or value is constructed by the prefix tilde sigil ~. Rust Manual, Section 9.1.4 let mut gname : ~str = ~"annotations"; 22
  • 24. Moving Pointers Lose reference of owned pointer after it is transferred. fn main() { let owned = ~"All mine!"; println!("Whose is it? {:s}", owned); let stolen = owned; println!("Whose is it? {:s}", stolen); } 23
  • 25. fn main() { let owned = ~"All mine!"; let stolen = owned; println!("Whose is it? {:s}", owned); } owned.rs:4:34: 4:39 error: use of moved value: `owned` owned.rs:4 println!("Whose is it? {:s}", owned); ^~~~~ note: in expansion of format_args! <std-macros>:195:27: 195:81 note: expansion site <std-macros>:194:5: 196:6 note: in expansion of println! owned.rs:4:4: 4:41 note: expansion site owned.rs:3:8: 3:14 note: `owned` moved here because it has type `~str`, which is moved by default (use `ref` to override) owned.rs:3 let stolen = owned; ^~~~~~ error: aborting due to previous error 24
  • 26. fn main() { let owned = ~"All mine!"; let ref stolen = owned; println!("Whose is it? {:s}", owned); println!("Whose is it? {:s}", *stolen); } fn main() { let owned: ~str = ~"Mine, all mine!"; let ref stolen : ~str; stolen = &owned; println!("Whose is it? {:s}", *stolen); } 25
  • 27. fn main() { let owned: ~str = ~"Mine, all mine!"; let ref stolen : ~str; stolen = &owned; fn main() { let ref stolen : ~str; println!("Whose is it? {:s}", *stolen); } { let mine: ~str = ~"Mine, all mine!"; stolen = &mine; } println!("Whose is it? {:s}", *stolen); } 26
  • 28. lifetimes.rs:6:16: 6:21 error: borrowed value does not live long enough lifetimes.rs:6 stolen = &mine; ^~~~~ lifetimes.rs:1:11: 10:2 note: reference must be valid for the block at 1:10... ... lifetimes.rs:4:4: 7:5 note: ...but borrowed value is only valid for the block at 4:3 … fn main() { let ref stolen : ~str; { let mine: ~str = ~”Mine!"; stolen = &mine; } ... } See Kiet’s blog to understand more about how the Rust compiler does this: http://ktt3ja.github.io/blog/2014/02/10/understanding-rusts-lifetime-inference/ 27
  • 29. Object’s Lifetime We cannot borrow an object for longer than that object may live! Length of “loan” Borrow Lifetimes 28
  • 30. fn bigger(s1: &str, s2: &str) -> &str { if s1.len() > s2.len() { s1 } else { s2 } } fn main() { let s: ~str = ~"Mine!"; let t: ~str = ~"Yours!"; println!("Whose is it? {:s}", bigger(s, t)); } 29
  • 31. borrow.rs:2:5: 2:46 error: cannot infer an appropriate lifetime due to conflicting requirements borrow.rs:2 if s1.len() > s2.len() { s1 } else { s2 } ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ borrow.rs:1:39: 3:2 note: first, the lifetime cannot outlive the anonymous lifetime #2 defined on the block at 1:38... borrow.rs:1 fn bigger(s1: &str, s2: &str) -> &str { fn bigger(s1: &str, s2: &str) -> &str { borrow.rs:2 if s1.len() > s2.len() { s1 } else { s2 } borrow.rs:3 } if s1.len() > s2.len() { s1 } else { s2 } borrow.rs:2:5: 2:46 note: ...so that if and else have compatible types (expected `&str` but found `&str`) } borrow.rs:2 if s1.len() > s2.len() { s1 } else { s2 } ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ borrow.rs:1:39: 3:2 note: but, the lifetime must be valid for the anonymous lifetime #3 defined on the block at 1:38... borrow.rs:1 fn bigger(s1: &str, s2: &str) -> &str { borrow.rs:2 if s1.len() > s2.len() { s1 } else { s2 } borrow.rs:3 } borrow.rs:2:5: 2:46 note: ...so that types are compatible (expected `&str` but found `&str`) borrow.rs:2 if s1.len() > s2.len() { s1 } else { s2 } ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ error: aborting due to previous error 30
  • 32. fn bigger<'a>(s1: &'a str, s2: &'a str) -> &'a str { if s1.len() > s2.len() { s1 } else { s2 } } Lifetime parameter: Rust infers minimum lifetime of all uses, and bind it to parameter 31
  • 33. fn bigger<'a>(s1: &'a str, s2: &'a str) -> &'a str { if s1.len() > s2.len() { s1 } else { s2 } } fn main() { let s: ~str = ~"Mine!"; let r: &str; { let t: ~str = ~"Yours!"; r = bigger(s, t); } println!("Whose is bigger? {:s}", r); } 32
  • 34. fn bigger<'a>(s1: &'a str, s2: &'a str) -> &'a str { if s1.len() > s2.len() { s1 } else { s2 } } fn main() { let s: ~str = ~"Mine!"; let r: &str; { let t: ~str = ~"Yours!"; r = bigger(s, t); } borrow2.rs:11:21: 11:22 error: borrowed value does not live long enough borrow2.rs:11 r = bigger(s, t); println!("Whose is bigger? {:s}", r); ^ borrow2.rs:5:11: 15:2 note: reference must be valid for the block at 5:10... } borrow2.rs:9:4: 12:5 note: ...but borrowed value is only valid for the block at 9:3 33
  • 35. Can we do this in Rust? 34
  • 36. fn set_name(gname: pname: ~str) { *gname = pname; } , 35
  • 37. fn set_name(gname : &mut ~str, pname : ~str) { *gname = pname; } fn main() { let mut gname : ~str = ~"annotations"; println!("gname = {:s}", gname); set_name(&mut gname, ~"frees"); println!("gname = {:s}", gname); } 36
  • 38. fn set_name(gname : &mut ~str, pname : ~str) { *gname = pname; } Why doesn’t Rust complain about the missing free? 37
  • 39. Frees? Where we are going, we don’t need frees! 38
  • 40. Memory Management Options Unmanaged (Explicit) C, C++ Up to programmer to free objects Managed (Automatic) Java, C#, Go, Python, Scheme Objects are automatically reclaimed Which is Rust? 39
  • 42. Forming Teams for PS3 For this problem set, you are required to work in a team of two or three people (except in cases where you were notified based on your PS2 teamwork that you should work alone for PS3, or where you make your own successful argument before February 19 that it is better for you to work alone). Your team may not be the same as your team for PS2, so you should either (1) find a new partner to work with for PS3, or (2) if you want to work with your PS2 partner again you must find one other person to join your team. If you do not end up on a well-formed team by the end of class on 18 February, you should contact me right away. 41