Programming Abstractions

Similar documents
Programming Abstractions

Programming Abstractions

PIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics

INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS

a data type is Types

CSCI 262 Data Structures. Arrays and Pointers. Arrays. Arrays and Pointers 2/6/2018 POINTER ARITHMETIC

Memory and C++ Pointers

CSE 12 Spring 2016 Week One, Lecture Two

Pointers and Memory 1

CMSC 341 Lecture 2 Dynamic Memory and Pointers

Intermediate Programming, Spring 2017*

Week 5, continued. This is CS50. Harvard University. Fall Cheng Gong

THE GOOD, BAD AND UGLY ABOUT POINTERS. Problem Solving with Computers-I

Comp 11 Lectures. Mike Shah. June 26, Tufts University. Mike Shah (Tufts University) Comp 11 Lectures June 26, / 57

CS 11 C track: lecture 5

Principles of Programming Pointers, Dynamic Memory Allocation, Character Arrays, and Buffer Overruns

GEA 2017, Week 4. February 21, 2017

Vector and Free Store (Pointers and Memory Allocation)

04-17 Discussion Notes

Pointers II. Class 31

CS201- Introduction to Programming Current Quizzes

Short Notes of CS201

CS201 - Introduction to Programming Glossary By

CS 106X, Lecture 16 More Linked Lists

The University of Nottingham

CA341 - Comparative Programming Languages

Implementing Abstractions

CSE 12 Spring 2018 Week One, Lecture Two

the gamedesigninitiative at cornell university Lecture 7 C++ Overview

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

Programming Abstractions

Chapter 18 Vectors and Arrays [and more on pointers (nmm) ] Bjarne Stroustrup

Object Reference and Memory Allocation. Questions:

Chapter 17 vector and Free Store. Bjarne Stroustrup

Vector and Free Store (Vectors and Arrays)

CA31-1K DIS. Pointers. TA: You Lu

Agenda. Peer Instruction Question 1. Peer Instruction Answer 1. Peer Instruction Question 2 6/22/2011

vector and Free Store

CS61C : Machine Structures

CS107 Handout 08 Spring 2007 April 9, 2007 The Ins and Outs of C Arrays

CS61C Machine Structures. Lecture 4 C Pointers and Arrays. 1/25/2006 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/

CS 31: Intro to Systems Pointers and Memory. Kevin Webb Swarthmore College October 2, 2018

Lecture 9. Pointer, linked node, linked list TDDD86: DALP. Content. Contents Pointer and linked node. 1.1 Introduction. 1.

CS 31: Intro to Systems Pointers and Memory. Martin Gagne Swarthmore College February 16, 2016

CSCI 262 Data Structures. The Big 3. Copy Constructor. Destructor. Assignment Operator 3/4/ The Big 3

Introducing C++ to Java Programmers

Programming Language Implementation

Chapter 17 vector and Free Store

Object-Oriented Programming for Scientific Computing

Arrays. Returning arrays Pointers Dynamic arrays Smart pointers Vectors

Memory Leak. C++: Memory Problems. Memory Leak. Memory Leak. Pointer Ownership. Memory Leak

About this exam review

CS2141 Software Development using C/C++ C++ Basics

Linked Memory. Pointers Linked Lists. September 21, 2017 Cinda Heeren / Geoffrey Tien 1

Operating Systems CMPSCI 377, Lec 2 Intro to C/C++ Prashant Shenoy University of Massachusetts Amherst

Separate Compilation Model

Lecture 14. No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions?

Consider the above code. This code compiles and runs, but has an error. Can you tell what the error is?

CPSC 427: Object-Oriented Programming

Introduction to C. Robert Escriva. Cornell CS 4411, August 30, Geared toward programmers

Pointers and References

Discussion 1E. Jie(Jay) Wang Week 10 Dec.2

Consider the program...

Introduction to C. Zhiyuan Teo. Cornell CS 4411, August 26, Geared toward programmers

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings

内存管理. Memory management

A brief introduction to C programming for Java programmers

6. Pointers, Structs, and Arrays. 1. Juli 2011

Lecture 15a Persistent Memory & Shared Pointers

Chapter 17 vector and Free Store

Kurt Schmidt. October 30, 2018

CS 241 Honors Memory

Come and join us at WebLyceum

WHAT POINTERS REALLY ARE

III. Classes (Chap. 3)

Chapter 1 Getting Started

The vector Class and Memory Management Chapter 17. Bjarne Stroustrup Lawrence "Pete" Petersen Walter Daugherity Fall 2007

CS 106X, Lecture 14 Classes and Pointers

C++ and OO. l C++ classes and OO. l More Examples. l HW2. C++ for C Programmers by Ira Pohl

dynamically allocated memory char* x = new char; int* x = new int[n]; ???...?

CS 241 Data Organization Binary Trees

FORM 2 (Please put your name and form # on the scantron!!!!) CS 161 Exam II:

Introduction to C. Ayush Dubey. Cornell CS 4411, August 31, Geared toward programmers

Introduction to Linked Lists. Introduction to Recursion Search Algorithms CS 311 Data Structures and Algorithms

C++ Programming. Classes, Constructors, Operator overloading (Continued) M1 Math Michail Lampis

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

Programming Abstractions

The issues. Programming in C++ Common storage modes. Static storage in C++ Session 8 Memory Management

CS 61c: Great Ideas in Computer Architecture

COMP 2355 Introduction to Systems Programming

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018

Dynamic Allocation in C

CS102 C++ Exception Handling & Namespaces

Exercise: Inventing Language

A brief introduction to C++

C++ Programming. Pointers and Memory Management. M1 Math Michail Lampis

Introduction to C. Sean Ogden. Cornell CS 4411, August 30, Geared toward programmers

Arrays and Memory Management

2 2

+ Abstract Data Types

Transcription:

Programming Abstractions C S 1 0 6 X Cynthia Lee

Topics: Last week, with Marty Stepp: Making your own class Arrays in C++ This week: Memory and Pointers Revisit some topics from last week Deeper look at what a pointer is Hexadecimal! Dynamic Memory allocation Linked nodes Linked List data structure (if we have time) Binary tree data structure 2

Arrays (revisit from last week)

Arrays (11.3) type* name = new type[length]; A dynamically allocated array. The variable that refers to the array is a pointer. The memory allocated for the array must be manually released, or else the program will have a memory leak. (>_<) Another array creation syntax that we will not use*: type name[length]; A fixed array; initialized at declaration; can never be resized. Stored in a different place in memory; the first syntax uses the stack and the second uses the heap. (discussed later) * For 106X, I would like you to know this syntax and be able to diagram what it does, but Marty Stepp was right in that we won t generally be using it in code you write (for style/design reasons).

Arrays on the stack and heap void myfunction() { int x = 5; int y; int arr[2]; arr[1] = 3; int *heaparr = new int[2]; // bad -- memory leak coming! } Memory main() myfunction() x: y: arr: heaparr: What happens when myfunction() returns? 0x0

ArrayList (revisit from last week)

Freeing array memory delete[] name; Releases the memory associated with the given array Must be done for all arrays created with new Or else the program has a memory leak. (No garbage collector like Java) Leaked memory will be released when the program exits, but for long-running programs, memory leaks are bad and will eventually exhaust your RAM int* a = new int[3]; a[0] = 42; a[1] = -5; a[2] = 17;... delete[] a;

Destructor (12.3) // ClassName.h // ClassName.cpp ~ClassName(); ClassName::~ClassName() {... destructor: Called when the object is deleted by the program. (when the object goes out of {} scope; opposite of a constructor) Useful if your object needs to do anything important as it dies: saving any temporary resources inside the object freeing any dynamically allocated memory used by the object's members Does our ArrayList need a destructor? If so, what should it do?

Destructor solution // in ArrayList.cpp ArrayList::ArrayList() { myelements = new int[10](); mysize = 0; mycapacity = 10; } void ArrayList::~ArrayList() { delete[] myelements; }

Running out of space What if the client wants to add more than 10 elements? index 0 1 2 3 4 5 6 7 8 9 value 3 8 9 7 5 12 4 8 1 6 size 10 capacity 10 list.add(75); // add an 11th element index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 value 3 8 9 7 5 12 4 8 1 6 75 0 0 0 0 0 0 0 0 0 size 11 capacity 20 Answer: Resize the array to one twice as large. Make sure to free the memory used by the old array!

Resize solution // in ArrayList.cpp void ArrayList::checkResize() { if (mysize == mycapacity) { // create bigger array and copy data over int* bigger = new int[2 * capacity](); for (int i = 0; i < mycapacity; i++) { bigger[i] = myelements[i]; } delete[] myelements; myelements = bigger; mycapacity *= 2; } }

Heap memory works like a hotel registration desk (Congratulations Golden Globe winner Grand Budapest Hotel)

Only a creepy killer would access a hotel room that isn t theirs (either never was, or was but checked out already) (Another great film about unusual people who work at hotels)

Pointers Taking a deeper look at the syntax of that array on the heap

Memory addresses: the basics When you declare a variable, it is necessarily stored somewhere in memory You can ask for any variable's memory address with the & operator Memory addresses are usually written as hexadecimal (base-16 or hex ) numbers Ex: 0x28F620 Prefix 0x is a visual cue that this is a hex number (not really part of the number) Stack 0x28F620 12 0x0 Heap

Examples of the & operator int x = 42; int y; int a[4] = {91, -3, 85, 17}; double d1 = 3.0; double d2 = 3.2; cout << x << endl; // 42 cout << &x << endl; // 0x7f8e20 cout << y << endl; // 17 cout << &y << endl; cout << a << endl; // 0x7f8e24 cout << &a[0] << endl; // 0x7f8e28 cout << &a[1] << endl; // 0x7f8e2c cout << &a[2] << endl; cout << &d << endl; // 0x7f8e30

Pointer arithmetic Surprise! operators +, -, ++, -- work on pointers Incrementing a T* (pointer to type T) by 1 moves the pointer forward in memory to the next T

Thinking about what we just learned When we add 1 to a pointer, how much does the address change? int x = 42; int y; int a[4] = {91, -3, 85, 17}; double d1 = 3.0;... int* pi = &x; double* pd = &d1; cout << pi << endl; pi++; cout << pi << endl; cout << pd << endl; pd++; cout << pd << endl; A. You can t do ++ on a pointer to int B. pi++ adds 1 and pd++ adds 1, of course! C. pi++ adds 4 and pd++ adds 4 D. Other/none/more than one This is why the language has you specify double* and int* rather than just having a generic* type (although it does have one of those too void*).

Data types in C++ Each unique memory address describes one byte of memory space (1byte = 8bits, or 8 1 s and 0 s) We say memory is byte addressable int addresses are 4 apart (32bits) double addresses are 8 apart (64bits) The above is true on this system--may differ on other systems Of course C++ doesn't impose a standard, because that would be safe and convenient, and that s not how we roll... Bonus question: do int* and double* take up the (A) SAME or (B) DIFFERENT amounts of space?

2 nd look: Arrays on the stack and heap void myfunction() { int x = 5; int y; int arr[2]; arr[1] = 3; int *heaparr = new int[2]; // bad -- memory leak coming! } Memory main() myfunction() x: y: arr: heaparr: 0x0

Arrays are actually pointers Surprise! If you have a pointer p (see declaration of p below), you can use p[k] syntax to access memory k slots away from p (according to the size of the type pointed to) p[k] is equivalent to *(p+k) (An array variable is really just a pointer to the array's first element, and so pointers and array variables work the same for indexing.)... int a[4] = {91, -3, 85, 17};... int* p = a; p[1] = 5; p++; cout << *p << endl; *(p + 2) = 26; cout << p[2] << endl; cout << a[2] << endl; What prints here? A. 26, 26 B. 26, 85 C. 85, 26 D. 85, 85

In the news: Heartbleed Last spring, security experts warned that users of thousands of major websites needed to change their passwords due to potential exposure caused by the Heartbleed vulnerability Heartbleed exploited a buffer overrun bug in OpenSSL SSL is the layer that secures web interactions, i.e., it s what make the s in https:// mean something

In the news: Heartbleed The protocol allows you to send heartbeat messages, which basically say: Are you still there? If you are, repeat this word back to me: hello [0x0005 bytes]. Each char is one byte, so 5 letters Unfortunately, the software also let you send messages like this: Are you still there? If you are, repeat this word back to me: hello [0xFFFF bytes]. That s 65535 bytes much more than the length of hello! So the software would continue forlooping past the end of the hello array, sending information back Which causes an error, right? RIGHT?? Turns out, no.

Software engineering tip: Initialize pointers always! If not to a useful value, then at least to NULL. NULL initialization forces your program to crash (this is a good thing, really!) if you try to use the pointer without assigning it a proper value Common error: int* foo; never initialized *foo = 555; 0x28F620 Stack Prevention: int* foo = NULL; *foo = 555; Image is in the public domain: http://en.wikipedia.org/wiki/file:operation_upshot-knothole_-_badger_001.jpg Heap