What the (Pointers in Rust)

Slides:



Advertisements
Similar presentations
Lecture 10: Heap Management CS 540 GMU Spring 2009.
Advertisements

CS216: Program and Data Representation University of Virginia Computer Science Spring 2006 David Evans Lecture 11: Managing Memory
Memory allocation CSE 2451 Matt Boggus. sizeof The sizeof unary operator will return the number of bytes reserved for a variable or data type. Determine:
Informática II Prof. Dr. Gustavo Patiño MJ
CS 326 Programming Languages, Concepts and Implementation Instructor: Mircea Nicolescu Lecture 18.
CPSC 388 – Compiler Design and Construction
Chapter 8 Runtime Support. How program structures are implemented in a computer memory? The evolution of programming language design has led to the creation.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
15213 C Primer 17 September Outline Overview comparison of C and Java Good evening Preprocessor Command line arguments Arrays and structures Pointers.
CS216: Program and Data Representation University of Virginia Computer Science Spring 2006 David Evans Lecture 10: *&!%[]++
11 Values and References Chapter Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables.
David Notkin Autumn 2009 CSE303 Lecture 12 October 24, 2009: Space Needle.
Finalizers, this reference and static Sangeetha Parthasarathy 06/13/2001.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
1 Lecture07: Memory Model 5/2/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
1 C Basics Monday, August 30, 2010 CS 241. Announcements MP1, a short machine problem, will be released today. Due: Tuesday, Sept. 7 th at 11:59pm via.
CS216: Program and Data Representation University of Virginia Computer Science Spring 2006 David Evans Lecture 12: Automating Memory Management
Plan for Today Exam 1 Version control: git Concurrent Collatz Challenge Winner! Memory Management 1.
“Success consists of going from failure to failure without loss of enthusiasm.” Winston Churchill.
1 Programming Languages (CS 550) List Processing, Dynamic Memory Allocation and Garbage Collection Jeremy R. Johnson.
CSE 220 – C Programming malloc, calloc, realloc.
Dynamic Allocation in C
Buffer Overflow By Collin Donaldson.
CS/COE 0449 (term 2174) Jarrett Billingsley
Computer Organization and Design Pointers, Arrays and Strings in C
Chapter 6 CS 3370 – C++ Functions.
Overview 4 major memory segments Key differences from Java stack
C Primer.
Pointers & Dynamic Memory
Dynamic Memory Allocation
Storage Management.
CSE 303 Concepts and Tools for Software Development
CS 537 Section 1 Programming in Unix and C
CS 153: Concepts of Compiler Design November 28 Class Meeting
Pointers and Memory Overview
CSE 351 Section 1: HW 0 + Intro to C
Checking Memory Management
CSCI206 - Computer Organization & Programming
Programmazione I a.a. 2017/2018.
typedef typedef int Index; typedef char Letter; Index i; i = 17;
This pointer, Dynamic memory allocation, Constructors and Destructor
Advanced Programming Behnam Hatami Fall 2017.
Reaching const evaluation singularity
Clear1 and Clear2 clear1(int array[], int size) { int i; for (i = 0; i < size; i += 1) array[i] = 0; } clear2(int *array, int size) {
CSC 253 Lecture 8.
Storage.
CSC 253 Lecture 8.
Overview 4 major memory segments Key differences from Java stack
Chapter 15 Pointers, Dynamic Data, and Reference Types
Pointers, Dynamic Data, and Reference Types
Dynamic Memory Allocation
Memory Allocation CS 217.
Outline Defining and using Pointers Operations on pointers
Dynamic Memory Allocation (and Multi-Dimensional Arrays)
CISC/CMPE320 - Prof. McLeod
Lecture 18: Deep C Garbage Collection CS201j: Engineering Software
List Allocation and Garbage Collection
CS216: Program and Data Representation
Arrays and Pointers (part 2)
Arrays and Pointers (part 2)
15213 C Primer 17 September 2002.
Pointers, Dynamic Data, and Reference Types
Automating Memory Management
Classes and Objects Object Creation
CMPE 152: Compiler Design May 2 Class Meeting
SPL – PS3 C++ Classes.
SPL – PS2 C++ Memory Handling.
CMSC 202 Constructors Version 9/10.
Presentation transcript:

What the &~#@<!? (Pointers in Rust) Class 9 cs4414 Fall 2013 David Evans Jodhpur, India (Dec 2011)

Last 15 minutes: Forming Teams for PS3 Plan for Today Recap: Explicit vs. Automatic Memory Management More Advanced Managed Memory Systematic, Explicit Memory Management Last 15 minutes: Forming Teams for PS3

Memory Management Options Unmanaged (Explicit) Managed (Automatic) C, C++ Up to programmer to free objects Java, C#, Go, Python, Scheme Objects are automatically reclaimed

Garbage Collection Mark and Sweep Compacting Generational Go

(Advanced “comic book” version of GC)

Mark-and-sweep about:config / javascript.options.mem.gc_incremental

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!

Counting References { T x = new T (); … y = x; }

#define _Py_NewReference(op) ( \ (op)->ob_refcnt = 1) 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) 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))

Is Reference Counting Enough?

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

Memory Management Options Unmanaged (Explicit) Managed (Automatic) C, C++ Up to programmer to free objects Java, C#, Go, Python, Scheme Objects are automatically reclaimed Is bounds checking orthogonal to memory management?

#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: %s\n", t + 12); long int x = (long int) t + 12; printf("Reaching s: %s\n", (char *) x); return 0; }

gash> gcc -Wall managed.c gash>./a.out Reaching s: Hello! #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: %s\n", t + 12); long int x = (long int) t + 12; printf("Reaching s: %s\n", (char *) x); return 0; } gash> gcc -Wall managed.c gash>./a.out Reaching s: Hello!

PLDI 1996

another paper from that conference… PLDI 1996

Complaints about my earlier tool: comp.os.linux post, August 1994

“Willy-Nilly” Memory Management Systematic Memory Management

Static Detection of Dynamic Memory Errors, David Evans, PLDI May 1996

Note: these are “compile-time” errors (just produced by a separate tool).

let mut gname : ~str = ~"annotations"; 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";

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); }

println!("Whose is it? {:s}", owned); } 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

println!("Whose is it? {:s}", owned); 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); }

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

lifetimes.rs:6 stolen = &mine; ^~~~~ 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/

Borrow Lifetimes We cannot borrow an object for longer than that object may live! Object’s Lifetime Length of “loan”

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));

fn bigger(s1: &str, s2: &str) -> &str { 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 { borrow.rs:3 } borrow.rs:2:5: 2:46 note: ...so that if and else have compatible types (expected `&str` but found `&str`) 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:2:5: 2:46 note: ...so that types are compatible (expected `&str` but found `&str`) error: aborting due to previous error fn bigger(s1: &str, s2: &str) -> &str { if s1.len() > s2.len() { s1 } else { s2 } }

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

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);

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); borrow2.rs:11:21: 11:22 error: borrowed value does not live long enough borrow2.rs:11 r = bigger(s, t); ^ 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

Can we do this in Rust?

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

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");

fn set_name(gname : &mut ~str, pname : ~str) { *gname = pname; } Why doesn’t Rust complain about the missing free?

Frees? Where we are going, we don’t need frees!

Memory Management Options Unmanaged (Explicit) Managed (Automatic) C, C++ Up to programmer to free objects Java, C#, Go, Python, Scheme Objects are automatically reclaimed Which is Rust?

Problem Set 3

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.