ALL ABOUT POINTERS C/C++ POINTERS

Similar documents
WHAT POINTERS REALLY ARE

Smart Pointers - What, Why, Which?

Project. C++: Smart Pointers. The Plan. Announcement. Memory Leak. Pointer Ownership. Today: STL 1 Wednesday: STL 2 Thursday: Smart Pointers

Smart Pointers. Some slides from Internet

Pointers. Developed By Ms. K.M.Sanghavi

COMP6771 Advanced C++ Programming

Pointers, Dynamic Data, and Reference Types

Vector and Free Store (Vectors and Arrays)

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

CSCI-1200 Data Structures Fall 2011 Lecture 24 Garbage Collection & Smart Pointers

Pointers and Memory 1

04-19 Discussion Notes

CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING C ++ Basics Review part 2 Auto pointer, templates, STL algorithms

1/29/2011 AUTO POINTER (AUTO_PTR) INTERMEDIATE SOFTWARE DESIGN SPRING delete ptr might not happen memory leak!

G52CPP C++ Programming Lecture 20

Short Notes of CS201

CS201 - Introduction to Programming Glossary By

Vector and Free Store (Pointers and Memory Allocation)

CSCI-1200 Data Structures Spring 2017 Lecture 27 Garbage Collection & Smart Pointers

The University of Nottingham

INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS

a data type is Types

04-17 Discussion Notes

Exception Namespaces C Interoperability Templates. More C++ David Chisnall. March 17, 2011

Dynamic Allocation in C

CS 11 C track: lecture 5

See the CS 2704 notes on C++ Class Basics for more details and examples. Data Structures & OO Development I

Class Information ANNOUCEMENTS

CA341 - Comparative Programming Languages

12. Pointers Address-of operator (&)

C++ Programming Lecture 4 Software Engineering Group

Managing Memory. (and low level Data Structures) Lectures 22, 23. Hartmut Kaiser.

Pointers and References

CS24 Week 3 Lecture 1

CS201 Some Important Definitions

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

Chapter 17 vector and Free Store

Introducing C++ to Java Programmers

C++ for Java Programmers

Arrays. Returning arrays Pointers Dynamic arrays Smart pointers Vectors

377 Student Guide to C++

Chapter 17 vector and Free Store

Object Oriented Software Design II


Modern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi

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

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

CSCI-1200 Data Structures Spring 2018 Lecture 25 Garbage Collection & Smart Pointers

Memory and C++ Pointers

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

Object Reference and Memory Allocation. Questions:

UEE1302 (1102) F10 Introduction to Computers and Programming (I)

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

CMSC 202 Section 010x Spring Justin Martineau, Tuesday 11:30am

the gamedesigninitiative at cornell university Lecture 7 C++ Overview

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

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

Chapter 17 vector and Free Store. Bjarne Stroustrup

CPSC 427: Object-Oriented Programming

CSE 307: Principles of Programming Languages

Variables. Data Types.

pointers + memory double x; string a; int x; main overhead int y; main overhead

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

Pointers and Arrays CS 201. This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book.

COMP 2355 Introduction to Systems Programming

CMSC 330: Organization of Programming Languages. Ownership, References, and Lifetimes in Rust

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

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

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

CS 241 Honors Memory

G52CPP C++ Programming Lecture 16

CSC1322 Object-Oriented Programming Concepts

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

Tokens, Expressions and Control Structures

Type Aliases. Examples: using newtype = existingtype; // C++11 typedef existingtype newtype; // equivalent, still works

Variables in C. Variables in C. What Are Variables in C? CMSC 104, Fall 2012 John Y. Park

CPSC 427: Object-Oriented Programming

CS 61c: Great Ideas in Computer Architecture

C++ for Java Programmers

Chapter 13: Copy Control. Overview. Overview. Overview

C++ Primer for CS175

Lecture 2, September 4

CS201 Latest Solved MCQs

6. Pointers, Structs, and Arrays. March 14 & 15, 2011

Fast Introduction to Object Oriented Programming and C++

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

CS3157: Advanced Programming. Outline

CSE 333. Lecture 11 - constructor insanity. Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington

Kurt Schmidt. October 30, 2018


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

Homework 4. Any questions?

Dynamic Allocation in C

Administrivia. Introduction to Computer Systems. Pointers, cont. Pointer example, again POINTERS. Project 2 posted, due October 6

Week 9 Part 1. Kyle Dewey. Tuesday, August 28, 12

Memory Management. CS31 Pascal Van Hentenryck CS031. Lecture 19 1

COMP322 - Introduction to C++ Lecture 02 - Basics of C++

Pointers! Arizona State University 1

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

Transcription:

ALL ABOUT POINTERS CS 403: Pointers, References, and Management Stefan D. Bruda Fall 2017 http://xkcd.com/138/ CS 403: Pointers, References, and Management (S. D. Bruda) Fall 2017 1 / 27 POINTERS C/C++ POINTERS What is a pointer? The index of a book contains pointers A URL (e.g., http://cs.ubishops.ca/home/cs403) is a pointer A street address is a pointer What is then a forwarding address? a pointer to a pointer! OK, so what is then a (C/C++) pointer? Often need to refer to some object without making a copy of the object itself Computer memory contains data which can be accessed using an address A pointer is nothing more than such an address Alternatively, computer memory is like an array holding data A pointer then is an index in such an array What are pointers physically? Since a pointer is an address, it is usually represented internally as unsigned int Pointers can (just as array indices) be stored in variables. d vx; vx is a variable of type d d* px; px is a (variable holding a) pointer to a variable of type d &vx denotes the address of vx (i.e., a pointer, of type d*) *px denotes the value from the memory location pointed at by px, of type d (we thus dereference px) 10 int x = 10; int* px = &x; int** ppx = &px; x px 7830 ppx 8991 7830 8991 9001 (&x) (&px) (&ppx) *px = x + 1; cout << x; 11 CS 403: Pointers, References, and Management (S. D. Bruda) Fall 2017 2 / 27 CS 403: Pointers, References, and Management (S. D. Bruda) Fall 2017 3 / 27

POINTER TYPES POINTER ARITHMETIC Do we need a type for a pointer? Why? So that we know what is the type of the thing we are referring to Always? Yes, unless the pointer does not point to anything (void*) int x=10; void* p = &x; int * pi; float* pf; pi = (int*)p; pf = (float*)p; cout << "Pointer " << p << " holds the int: "<< *pi << "...and the float: " << *pf; There is nothing preventing a pointer to point to garbage Special pointer (of what type?): NULL or 0, which points to nothing The types of pointers do matter: 1 We know what we get when we dereference a pointer 2 We can do meaningful pointer arithmetic Meaningful pointer arithmetic?!? int i=10; long j=10; int *x = &i; long *y = &j; int *x1 = x + 3; long *y1 = y + 3; int *x2 = x - 2; long *y2 = y - 2; 0x34791B 0x34791C 0x34791D x 2 x x+3 0x34791E 0x34791F 0x347920 0x347921 0x347922 0x347923 0x347924 0x437925 0x437926 0x437927 CS 403: Pointers, References, and Management (S. D. Bruda) Fall 2017 4 / 27 CS 403: Pointers, References, and Management (S. D. Bruda) Fall 2017 5 / 27 POINTER ARITHMETIC POINTER ARITHMETIC The types of pointers do matter: 1 We know what we get when we dereference a pointer 2 We can do meaningful pointer arithmetic Meaningful pointer arithmetic?!? int i=10; long j=10; int *x = &i; long *y = &j; int *x1 = x + 3; long *y1 = y + 3; int *x2 = x - 2; long *y2 = y - 2; x 2 x y x+3 The types of pointers do matter: 1 We know what we get when we dereference a pointer 2 We can do meaningful pointer arithmetic Meaningful pointer arithmetic?!? int i=10; long j=10; int *x = &i; long *y = &j; int *x1 = x + 3; long *y1 = y + 3; int *x2 = x - 2; long *y2 = y - 2; y 2 x 2 x y x+3 y+3 0x437927 0x437926 0x437925 0x347924 0x347923 0x347922 0x347921 0x347920 0x34791F 0x34791E 0x34791D 0x34791C 0x34791B 0x437927 0x437926 0x437925 0x347924 0x347923 0x347922 0x347921 0x347920 0x34791F 0x34791E 0x34791D 0x34791C 0x34791B CS 403: Pointers, References, and Management (S. D. Bruda) Fall 2017 5 / 27 CS 403: Pointers, References, and Management (S. D. Bruda) Fall 2017 5 / 27

C ARRAYS AND POINTERS C ARRAYS VERSUS POINTERS A C array is just a pointer to its content: float nums[6] = {1,2,3 nums 72466 10201 nums[0] 72466 nums[1] nums[2] 1.0 2.0 3.0 nums[3] nums[4] nums[5] 72467 72468 72469 72470 72471 In addition, when you declare an array (contiguous) memory space is reserved to hold its elements Pointer arithmetic goes hand in hand with C arrays float nums[6] = {1,2,3; float* p1 = nums; float* p2 = nums + 1; cout << nums[1] << " " << p1[1] << " " << p2[1]; // 2.0 2.0 3.0 In fact arr[index] is perfectly equivalent with *(arr+index) The following declarations mean almost the same thing: int* numsp; int numsa[20]; Indeed: numsa[2] = 17; Good numsp[2] = 17; Disaster! Prize for the most uninformative error message goes to Segmentation fault. However it is perfectly good to do: int numsp[] = {1,2,3; In other words, one do not have to provide the dimension for an array if one initializes it at the moment of declaration (e.g., by providing a literal array) CS 403: Pointers, References, and Management (S. D. Bruda) Fall 2017 6 / 27 CS 403: Pointers, References, and Management (S. D. Bruda) Fall 2017 7 / 27 ARRAYS, POINTERS, AND FUNCTIONS ARRAYS, POINTERS, AND FUNCTIONS (CONT D) #include <iostream> using namespace std; void translate(char a) { if (a == A ) a = 5 ; else a = 0 ; void translate(char* array, int size) { for (int i = 0; i < size; i++) { if (array[i] == A ) array[i] = 5 ; else array[i] = 0 ; #include <iostream> using namespace std; void translate(char *a) { if (*a == A ) *a = 5 ; else *a = 0 ; void translate(char* array, int size) { for (int i = 0; i < size; i++) { if (array[i] == A ) array[i] = 5 ; else array[i] = 0 ; char mark = A ; char marks[5] = { A, F, A, F, F ; translate(mark); translate(marks,5); cout << mark << "\n"; for (int i = 0; i < 5; i++) cout << marks[i] << " "; cout << "\n"; Output: A 5 0 5 0 0 char mark = A ; char marks[5] = { A, F, A, F, F ; translate(&mark); translate(marks,5); cout << mark << "\n"; for (int i = 0; i < 5; i++) cout << marks[i] << " "; cout << "\n"; Output: 5 5 0 5 0 0 CS 403: Pointers, References, and Management (S. D. Bruda) Fall 2017 8 / 27 CS 403: Pointers, References, and Management (S. D. Bruda) Fall 2017 9 / 27

POINTERS AND FUNCTIONS CALL BY REFERENCE POINTER In C and C++ an argument can be passed to a function using: Call by value: the value of the argument is passed; argument changes will not be seen outside the function int afunction(int i); Call by reference: the pointer to the argument is passed to the function; argument changes will be seen outside the function int afunction(int* i); Used for output arguments (messy, error prone syntax) Call by constant reference: the pointer to the argument is passed to the function; but the function is not allowed to change the argument int afunction(const int* i); more useful: int afunction(const char* i); Used for bulky arguments (still messy syntax) foo.cc void increment (int* i) { *i = *i + 1; void increment1 (const int* i) { *i = *i + 1; int n = 0; increment(&n); increment1(&n); g++ -Wall foo.cc foo.cc: In function void increment1(const int *) : foo.cc:9: assignment of read-only location CS 403: Pointers, References, and Management (S. D. Bruda) Fall 2017 10 / 27 CS 403: Pointers, References, and Management (S. D. Bruda) Fall 2017 11 / 27 CALL BY REFERENCE foo.cc no more messy syntax! void increment (int& i) { i = i + 1; void increment1 (const int& i) { i = i + 1; int n = 0; increment(n); increment1(n); g++ -Wall foo.cc foo.cc: In function void increment1(const int &) : foo.cc:9: assignment of read-only reference i CS 403: Pointers, References, and Management (S. D. Bruda) Fall 2017 12 / 27 REFERENCES AND CALLING CONVENTIONS A reference is just like a pointer, but with a nicer interface An alias to an object, but it hides such an indirection from the programmer Must be typed and can only refer to the declared type (int &r; can only refer to int, etc) Must always refer to something in C++ but may refer to the null object in Java Explicit in C++ (unary operator &) implicit in Java for all objects and nonexistent for primitive types Implicit calling conventions: What Java C++ Primitive types value value (int, float, etc.) Arrays reference value Objects reference value In C++ everything is passed by value unless explicitly stated otherwise (by declaring the respective parameter as a reference) C arrays are apparently passed by reference, but only because of the array structure (pointer + content) In Java there is no other way to pass arguments than the implicit one CS 403: Pointers, References, and Management (S. D. Bruda) Fall 2017 13 / 27

POINTERS AND SIMPLE LINKED LISTS DYNAMIC MEMORY MANAGEMENT struct cons_cell { int car; cons_cell* cdr; ; typedef cons_cell* list; const list nil = 0; int null (list cons) { return cons == nil; // must use pointers, else the type is infinitely recursive list cons (int car, list cdr = nil) { list new_cons = new cons_cell; new_cons -> car = car; // (*new_cons).car = car; new_cons -> cdr = cdr; // (*new_cons).cdr = cdr; return new_cons; int car (list cons) { return cons -> car; list cdr (list cons) { return cons -> cdr; new allocates memory for your data. The following are (somehow) equivalent: char message[256]; char* pmessage; pmessage = new char[256]; Exception: message takes care of itself (i.e., gets deleted when it is no longer in use), whereas pmessage however must be explicitly deleted when it is no longer needed: delete[] pmessage; Perrils of not using new: list cons (int car, list cdr = nil) { cons_cell new_cons; new_cons.car = car; new_cons.cdr = cdr; return &new_cons; list bad = cons(1); cout << car(bad); Boom! CS 403: Pointers, References, and Management (S. D. Bruda) Fall 2017 14 / 27 CS 403: Pointers, References, and Management (S. D. Bruda) Fall 2017 15 / 27 DYNAMIC MEMORY MANAGEMENT (CONT D) SAY NO TO MEMORY LEAKS cons_cell* foo () { cons_cell c; list l = new cons_cell; return...; Heap Conclusion: cons_cell foo returns l zap!! int i; foo(); Stack foo returns c main: i int foo: c zap!! cons_cell If you create something using new then you must eventually delete it using delete list rmth (list cons, int which) { list place = cons; for (int i = 0; i < which - 1; i++) { if (null(place)) break; place = place -> cdr; if (! null(place) ) { if (null(cdr(place))) place -> cdr = nil; else { list to delete = cdr(place); place -> cdr = cdr(place -> cdr); delete to delete; return cons; CS 403: Pointers, References, and Management (S. D. Bruda) Fall 2017 16 / 27 CS 403: Pointers, References, and Management (S. D. Bruda) Fall 2017 17 / 27

THE PERILS OF DELETE An object and all the pointers to it (when they are dereferenced) alias the same location Assigning a value through one channel will affect all the other channels management through one channel will affect all the other channels as well Thou shall not leak memory, but also: Thou shall not leave stale (dangling) pointers behind char* str = new char[128]; allocate memory for str strcpy(str,"hello"); put something in there ( hello ) char* p = str; delete [] p; p points to the same thing hello is gone, str is a stale pointer!! Thou shall not dereference deleted pointers strcpy(str,"hi"); str already deleted!! Thou shall not delete a pointer more than once delete str; str already deleted!! You can however delete null pointers as many times as you wish! So assign zero to deleted pointers whenever possible (not a panaceum) CS 403: Pointers, References, and Management (S. D. Bruda) Fall 2017 18 / 27 THE PERILS OF DELETE (CONT D) struct prof { char* name; char* dept; ; char *csc = new char[30]; strcpy (csc,"computer Science"); prof *stefan, *dimitri, *bruda; stefan = new prof; dimitri = new prof; stefan >name = new char[30]; dimitri >name = new char[30]; strcpy(stefan >name,"stefan Bruda"); strcpy(dimitri >name,"dimitri Vouliouris"); stefan >dept = csc; dimitri >dept = csc; // Delete dimitri delete dimitri >name; delete dimitri >dept; delete dimitri; Exogenous data OK??? Indigenous data // Copy stefan bruda = new prof; // (a) Shallow copying bruda >name = stefan >name; bruda >dept = stefan >dept; // Can we delete stefan now?? // (b) Deep copying bruda >name = new char[30]; bruda >dept = new char[30]; strcpy(bruda.name,stefan.name); strcpy(bruda.dept,stefan.dept); // Can we delete stefan now?? CS 403: Pointers, References, and Management (S. D. Bruda) Fall 2017 19 / 27 POINTERS AS FIRST-ORDER C++ OBJECTS EXAMPLE OF USE They are objects that look and feel like pointers, but are smarter Look like pointers = have the same interface that pointers do They need to support pointer operations like dereferencing (operator*) and indirection (operator ->) An object that looks and feels like something else is called a proxy object, or just proxy Smarter = do things that regular pointers don t Such as memory management Simplest example: auto_ptr, included in the standard C++ library. header: <memory> template <class T> class auto_ptr { T* ptr; public: explicit auto_ptr(t* p = 0) : ptr(p) { ~auto_ptr() {delete ptr; T& operator*() {return *ptr; T* operator->() {return ptr; //... ; Instead of: void foo() { MyClass* p(new MyClass); p->dosomething(); delete p; We use: void foo() { auto_ptr<myclass> p(new MyClass); p->dosomething(); p now cleans up after itself. CS 403: Pointers, References, and Management (S. D. Bruda) Fall 2017 20 / 27 CS 403: Pointers, References, and Management (S. D. Bruda) Fall 2017 21 / 27

WHY USE: LESS BUGS Automatic cleanup: They clean after themselves, so there is no chance you will forget to deallocate Automatic initialization: You all know what a non-initialized pointer does; the default constructor now does the initialization to zero for you Stale pointers: As stated before, stale pointers are evil: MyClass* p(new MyClass); MyClass* q = p; delete p; // p->dosomething(); // We don t do that, p is stale p = 0; // we do this instead q->dosomething(); // Ouch, q is still stale! Smart pointers can set their content to 0 once copied, e.g. template <class T> auto_ptr<t>& auto_ptr<t>::operator=(auto_ptr<t>& rhs) { if (this!= &rhs) { delete ptr; ptr = rhs.ptr; rhs.ptr = 0; return *this; CS 403: Pointers, References, and Management (S. D. Bruda) Fall 2017 22 / 27 STALE POINTERS (CONT D) The simplistic strategy to change ownership may not be suitable; other strategies can be implemented: Deep copy the source into the target Transfer ownership by letting p and q point to the same object but transfer the responsibility for cleaning up from p to q Reference counting: count the references to the object and delete it only when the count reaches zero Copy on write: use reference counting as long as the pointer is not modified, and just before it gets modified copy it and modify the copy Each strategy has advantages and disadvantages and are suitable for certain kind of applications CS 403: Pointers, References, and Management (S. D. Bruda) Fall 2017 23 / 27 WHY USE: EXCEPTION SAFETY WHY USE: GARBAGE COLLECTION, EFFICIENCY Our old, simple example... void foo() { MyClass* p(new MyClass); p->dosomething(); delete p;... generates a memory leak (at best!) whenever DoSomething throws an exception We could of course take care of it by hand (pretty awkward; imagine now that you have some loops threw in for good measure): void foo() { MyClass* p(new MyClass); try { p = new MyClass; p->dosomething(); delete p; catch (...) {delete p; throw; With smart pointers we just let p clean up by itself. C++ typically lacks garbage collection But this can be implemented using smart pointers Simplest form of garbage collection: reference counting Other, more sophisticated strategies can be implemented in the same spirit Remember, we can also have static variables in a class, and other goodies Generally, garbage collection = reference counting + memory compaction If the object pointed at does not change, there is no need to copy it; nuff said Copying takes both time and space Copy on write is our friend here C++ strings are typically implemented in this manner string s("hello"); string t = s; // t and s point to the same // buffer of characters t += " there!"; // a new buffer is allocated for t before // appending, so that s is unchanged CS 403: Pointers, References, and Management (S. D. Bruda) Fall 2017 24 / 27 CS 403: Pointers, References, and Management (S. D. Bruda) Fall 2017 25 / 27

WHY USE: STL CONTAINERS HOW TO CHOOSE YOUR SMART POINTER STL containers (such as vector) store objects by value So you cannot store objects of a derived type: class Base { /*...*/ ; class Derived : public Base { /*...*/ ; Base b; Derived d; vector<base> v; v.push_back(b); // OK v.push_back(d); // no cake You go around this by using pointers: vector<base*> v; The simplest smart pointer auto ptr is probable suited for local variables A copied pointer is usually useful for class members Think copy constructor and you think deep copy Due to their nature STL containers require garbage collected pointers (e.g., reference counting) Whenever you have big objects you are probably better off using copy on write pointers v.push_back(new Base); v.push_back(new Derived); // OK // OK // obligatory cleanup, disappears when using smart pointers for (vector<base*>::iterator i = v.begin(); i!= v.end(); ++i) delete *i; CS 403: Pointers, References, and Management (S. D. Bruda) Fall 2017 26 / 27 CS 403: Pointers, References, and Management (S. D. Bruda) Fall 2017 27 / 27