1 CSC 222: Computer Programming II Spring 2004 Pointers and dynamic memory  pointer type  dereference operator (*), address-of operator (&)  sorting.

Slides:



Advertisements
Similar presentations
1 CSC 222: Computer Programming II Spring 2004  vectors  library, templated  advantages over arrays:  const-reference parameters  growable vectors.
Advertisements

Pointers Revisited l What is variable address, name, value? l What is a pointer? l How is a pointer declared? l What is address-of (reference) and dereference.
Lecture 3 Feb 4 summary of last week’s topics and review questions (handout) Today’s goals: Chapter 1 overview (sections 1.4 to 1.6) c++ classes constructors,
Engineering Problem Solving With C++ An Object Based Approach Chapter 9 Pointers and Creating Data Structures.
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
Review of pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
Main Index Contents 11 Main Index Contents Container Types Container Types Sequence Containers Sequence Containers Associative Containers Associative Containers.
Pointers1 Pointers & Dynamic Arrays Allocating memory at run-time.
1 ES 314 Advanced Programming Lec 3 Sept 8 Goals: complete discussion of pointers discuss 1-d array examples Selection sorting Insertion sorting 2-d arrays.
ARRAYS AND POINTERS Although pointer types are not integer types, some integer arithmetic operators can be applied to pointers. The affect of this arithmetic.
Review on pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
1 Chapter 6 Lists Plus. ADT Sorted List Operations Transformers n MakeEmpty n InsertItem n DeleteItem Observers n IsFull n LengthIs n RetrieveItem Iterators.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
Shallow Versus Deep Copy and Pointers Shallow copy: when two or more pointers of the same types point to the same memory – They point to the same data.
Review of C++ Programming Part II Sheng-Fang Huang.
CSE 332: C++ templates and generic programming I Motivation for Generic Programming in C++ We’ve looked at procedural programming –Reuse of code by packaging.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
Pointer Data Type and Pointer Variables
Modular Programming Chapter Value and Reference Parameters t Function declaration: void computesumave(float num1, float num2, float& sum, float&
1 CSC 222: Computer Programming II Spring 2004 Searching and efficiency  sequential search  big-Oh, rate-of-growth  binary search Class design  templated.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 4: Linked Lists Data Abstraction & Problem Solving with.
Pointers CS362. Pointers A Pointer is a variable that can hold a memory address Pointers can be used to: Indirectly reference existing variables (sometimes.
1 CSC 222: Computer Programming II Spring 2004 Pointers and linked lists  human chain analogy  linked lists: adding/deleting/traversing nodes  Node.
Main Index Contents 11 Main Index Contents Week 3 – The Vector Container.
Overloading Binary Operators Two ways to overload –As a member function of a class –As a friend function As member functions –General syntax Data Structures.
SEN 909 OO Programming in C++ Final Exam Multiple choice, True/False and some minimal programming will be required.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 5 An Array Class Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
Pointers OVERVIEW.
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 4 Pointers and Dynamic Arrays Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
C++ Data Types Structured array struct union class Address pointer reference Simple IntegralFloating char short int long enum float double long double.
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
Object-Oriented Programming in C++
Overloading Operator MySting Example. Operator Overloading 1+2 Matrix M 1 + M 2 Using traditional operators with user-defined objects More convenient.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
1 Chapter 16 Linked Structures Dale/Weems. 2 Chapter 16 Topics l Meaning of a Linked List l Meaning of a Dynamic Linked List l Traversal, Insertion and.
CPSC 252 The Big Three Page 1 The “Big Three” Every class that has data members pointing to dynamically allocated memory must implement these three methods:
1 CSC 222: Computer Programming II Spring 2004 Sorting and recursion  insertion sort, O(N 2 )  selection sort  recursion  merge sort, O(N log N)
Data Structures Using C++1 Chapter 3 Pointers Dr. Liu.
Review 1 List Data Structure List operations List Implementation Array Linked List.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
Lecture – Pointers1 C++ Pointers Joseph Spring/Bob Dickerson School of Computer Science Operating Systems and Computer Networks Based on notes by Bob Dickerson.
Lecture 10: 2/17/2003CS148 Spring CS148 Introduction to Programming II Ayman Abdel-Hamid Department of Computer Science Old Dominion University Lecture.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class.
1 CSC 222: Computer Programming II Spring 2004 Stacks and recursion  stack ADT  push, pop, top, empty, size  vector-based implementation, library 
Object Oriented Programming COP3330 / CGS5409.  Aggregation / Composition  Dynamic Memory Allocation.
CSC 221: Computer Programming I Fall 2001  arrays  homogeneous collection of items, accessible via an index  initializing/traversing/displaying arrays.
Chapter 1 C++ Basics Review (Section 1.4). Classes Defines the organization of a data user-defined type. Members can be  Data  Functions/Methods Information.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
CS162 - Topic #6 Lecture: Pointers and Dynamic Memory –Review –Dynamically allocating structures –Combining the notion of classes and pointers –Destructors.
1 CS 132 Spring 2008 Chapter 5 Linked Lists p
CSC Pointers Powerful feature of the C++ language One of the most difficult to master Essential for construction of interesting data structures.
CSC 533: Programming Languages Spring 2016
CSC 533: Programming Languages Spring 2015
Motivation and Overview
Pointers Revisited What is variable address, name, value?
Dynamic Memory Allocation
Object Oriented Programming COP3330 / CGS5409
Chapter 15 Pointers, Dynamic Data, and Reference Types
Chapter 12 Pointers and Memory Management
Chapter 16 Linked Structures
9-10 Classes: A Deeper Look.
CS410 – Software Engineering Lecture #5: C++ Basics III
COP 3330 Object-oriented Programming in C++
CSC 533: Programming Languages Spring 2019
9-10 Classes: A Deeper Look.
Presentation transcript:

1 CSC 222: Computer Programming II Spring 2004 Pointers and dynamic memory  pointer type  dereference operator (*), address-of operator (&)  sorting lists of pointers  dynamic memory allocation, new operator  dynamic arrays and vectors  destructors, copy constructors, assignment operators

2 Sorting revisited… recall from lectures & hw4  sorting involves some # of inspection and some # of swaps  the amount of time required for a swap is dependent on the size of the values vector nums(10000); SelectSort(nums); vector names(10000); SelectSort(names); vector audits(10000); SelectSort(audits); to selection sort a list of 10,000 items:  must perform 9,999 swaps ( = 29,997 assignments)  if the items being sorted are large, then swap time can add up! POSSIBLE WORKAROUNDS?

3 Lists of pointers idea: instead of storing the (potentially large) items in the vector, store them elsewhere and keep pointers (addresses) "foo""bar""biz""baz""boo""zoo"... can sort as before  when comparing values, have to follow the pointers to the actual data  when swapping, copy the pointers, not the data values pointers are addresses (integers), so copying is fast note: since all pointers are same size, swap time is independent of data size

4 a pointer is nothing more than an address (i.e., an integer)  can declare a pointer to a particular type of value using * int * p; string * q; TYPE * PTR; Pointers ??? p q PTR operations on pointers:  dereference operator: given a pointer to some memory location, can access the value stored there using *  address-of operator: given a memory cell, can get its address (i.e., a pointer to it) using & 4 p cout << *p << endl; x 7 p = &x;

5 int * p; int x = 6; p = &x; cout << *p << endl; x++; cout << *p << endl; *p += 3; cout << x; Pointer examples using pointers and operations, can create aliases for memory locations  in the above examples, x and *p refer to the same location reminiscent of reference parameters?

6 Reference parameters and pointers reference parameters are implemented using pointers  when you pass an argument by-reference, you are really passing a pointer to it implicitly,  the address of the argument is obtained and passed in to the parameter  each access of the parameter first dereferences the address void Foo(int & x) { cout << x << endl; } int a = 3; Foo(a); void Foo(int * x) { cout << *x << endl; } int a = 3; Foo(&a); what you write…what C++ sees…

7 Tracing code… template void Swap(Type & x, Type & y) { Type temp = x; x = y; y = temp; } int a = 5, b = 9; Swap(a, b); cout << a << " " << b << endl; int * p1 = &a; int * p2 = &b; cout << a << " " << b << endl; Swap(*p1, *p2); cout << a << " " << b << endl; cout << *p1 << " " << *p2 << endl; Swap(p1, p2); cout << a << " " << b << endl; cout << *p1 << " " << *p2 << endl;

8 Reimplementing selection sort template void SelectionSortPtr(vector & nums, int low, int high) { for (int i = low; i <= high-1; i++) { int indexOfMin = i; for (int j = i+1; j <= high; j++) { if (*(nums[j]) < *(nums[indexOfMin])) { indexOfMin = j; } Comparable * temp = nums[i]; nums[i] = nums[indexOfMin]; nums[indexOfMin] = temp; } template void SelectionSortPtr(vector & nums) { SelectionSortPtr(nums, 0, nums.size()-1); } the vector contains pointers to comparable values when comparing values, dereference (note: must parenthesize since * has higher precedence than [] ) when swapping, swap pointers, not values

9 Reimplementing merge sort template void MergePtr(vector & nums, int low, int high) { vector copy; int size = high-low+1, middle = 1 + (low+high)/2; // middle rounds up if even int front1 = low, front2 = middle; for (int i = 0; i < size; i++) { if (front2 > high || (front1 < middle && *(nums[front1]) < *(nums[front2]))) { copy.push_back(nums[front1]); front1++; } else { copy.push_back(nums[front2]); front2++; } for (int k = 0; k < size; k++) { nums[low+k] = copy[k]; } template void MergeSortPtr(vector & nums, int low, int high) { if (low < high) { int middle = (low + high)/2; MergeSortPtr(nums, low, middle); MergeSortPtr(nums, middle+1, high); MergePtr(nums, low, high); } template void MergeSortPtr(vector & nums) { MergeSortPtr(nums, 0, nums.size()-1); } again, vector stores pointers dereference before comparing swap pointers, not values

10 Dynamic memory so far, we have only considered pointers to existing (static) memory  when you declare a variable, the compiler automatically allocates memory for it and reclaims that memory location when the lifetime ends we can also use pointers to access dynamically-allocated memory  i.e., memory locations that are explicitly created/destroyed on user demand the new operator returns a pointer to a new, dynamically-allocated memory location int * iptr = new int; *iptr = 4; cout << *iptr << endl; string * sptr = new string; *sptr = "foo"; cout << *p << endl;

11 Testing the sorts #include #include "Sorts.h" using namespace std; int main() { vector words1, words2; string str; while (cin >> str) { string * sptr = new string; *sptr = str; words1.push_back(sptr); words2.push_back(sptr); } MergeSortPtr(words1); for (int i = 0; i < words1.size(); i++) { cout << *(words1[i]) << endl; } SelectionSortPtr(words2); for (int i = 0; i < words2.size(); i++) { cout << *(words2[i]) << endl; } return 0; } here, the test program: creates two vectors of string pointers reads and stores words in the vectors note: only creates one copy of the word, has two different pointers to it sorts the vectors and displays the contents note: new requires a class constructor here, the default constructor for string (with no arguments is used) could have used 1-argument constructor string * sptr = new string(str);

12 Vector class implementation recall: vector is not a built-in type in C++  it is a class, defined in the library C++ has a built-in array type, which is the underlying data structure for vector  like vector, an array is a contiguous sequence of items, accessible via indexing int nums[100]; for (int i = 0; i < 100; i++) { nums[i] = 0; } unlike vectors, arrays:  do not have size info associated with them (you must keep track yourself)  the size of the array must be known at compile time (& stays fixed)  no bounds-checking is done for arrays  when you pass an array by-value, the array elements can still be changed! WHY?

13 Arrays as pointers inutitively, we think of an array as a contiguous sequence of locations … int nums[100]; nums technically, a C++ array is implemented as a pointer to the sequence … nums to access nums[i] : follow the nums pointer to nums[0], then move ahead i locations in memory

14 Arrays as parameters recall how a value parameter works:  a copy of the argument is stored in the parameter  changes to the parameter only affect the copy but what if the parameter is a pointer (e.g., an array)? void Init(int nums[], int size) { for (int i = 0; i < size; i++) { nums[i] = 0; } int grades[20]; Init(grades, 20); … grades since an array is really a pointer, passing an array by-value still allows for access to the original array elements note: this is equivalent to: void Init(int * nums, int size)

15 Dynamic arrays the pointer nature of arrays gives us a way around the compile-time size restriction  ordinary declaration: int nums[20]; creates the nums pointer, allocates space for 20 ints, and makes nums point to it  can separate the pointer declaration and memory allocation steps int * nums; creates the nums pointer (to an int) nums = new int[20]; allocates space for 20 ints and points nums to it the new operator "dynamically" allocates storage, size can be determined during execution cout << "How many numbers? "; cin >> size; int * nums; nums = new int[size];

16 Vectors and dynamic arrays the underlying data structure of a vector is a dynamically-allocated array template class vector { public: vector(int size = 0) { vecLength = size; vecList = new Type[size]; } int size() { return vecLength; } Type & operator[](int index) { return vecList[index]; } // OTHER MEMBER FUNCTIONS private: Type * vecList; int vecLength; }; MEMBER FUNCTIONS vector object

17 Resizing a vector you can't resize an array, but you can create a new (bigger) array and copy void resize(int newSize) { Type * newList = new Type[newSize];// ALLOCATE A NEW ARRAY OF DESIRED SIZE int numToCopy = min(newSize, vecLength);// DETERMINE HOW MANY ITEMS TO COPY for (int i = 0; i < numToCopy; i++) {// AND COPY FROM vecLIST TO THE newList newList[i] = vecList[i]; } delete[] vecList;// DEALLOCATE THE MEMORY IN vecList vecList = newList;// RESET vecList TO POINT TO THE NEW ARRAY vecLength = newSize;// AND RESET vecLength } note that dynamically-allocated memory is only accessible through a pointer  if you lose the pointer, then the memory is lost (will NOT be automatically reclaimed)  MEMORY LEAKAGE can eventually use up all free memory  any memory the programmer explicitly allocates using new must be explicitly deallocated using delete ( or delete[] for an array)

18 List & SortedList revisited recall the List and SortedList classes  List : stores a vector of items Add operation inserts item in order IsStored operation uses binary search to see if item is in the vector  SortedList : stores a vector of items Add operation inserts item in order AddFast operation adds at end IsStored checks to see if currently sorted if sorted, then perform binary search if not sorted, then merge sort the vector before binary search we could improve the performance of the List and SortedList classes by storing pointers in the vector  note: member functions are unchanged, so change is transparent to client  underlying data structure changes, and member functions that access it

19 ListPtr.h template class List { public: List () { /* does nothing */ } virtual void Add(const ItemType & item) { ItemType * newPtr = new ItemType(item); items.push_back(newPtr); } virtual bool IsStored(const ItemType & item) { for (int i = 0; i < items.size(); i++) { if (item == *(items[i])) { return true; } return false; } int NumItems() const { return items.size(); } void DisplayAll() const { for (int i = 0; i < items.size(); i++) { cout << *(items[i]) << endl; } protected: vector items; // storage for strings }; Add needs to allocate space for a copy, then add a pointer to that copy to the vector IsStored needs to dereference the pointers when comparing DisplayAll needs to dereference the pointers when displaying items stores pointers

20 SortedListPtr.h template class SortedList : public List { public: SortedList () { isSorted = true; } void Add(const ItemType & item) { ItemType * newPtr = new ItemType(item); items.push_back(newPtr); int i; for (i = items.size()-1; i > 0 && *(items[i-1]) > item; i--) { items[i] = items[i-1]; } items[i] = newPtr; } void AddFast(const ItemType & item) { ItemType * newPtr = new ItemType(item); items.push_back(newPtr); isSorted = false; } bool IsStored(const ItemType & item) { if (!isSorted) { MergeSortPtr(items); isSorted = true; } int left = 0, right = items.size()-1; while (left <= right) { int mid = (left+right)/2; if (item == *(items[mid])) { return true; } else if (item < *(items[mid])) { right = mid-1; } else { left = mid + 1; } return false; } private: bool isSorted; };

21 Timing the new SortedList... SortedList slist1, slist2; start = clock(); for (int i = 0; i < listSize; i++) { slist1.Add(randomData[i]); } found = slist1.IsStored("aaa"); stop = clock(); cout << "Simple sort/search required " << stop-start << " milliseconds" << endl; start = clock(); for (int i = 0; i < listSize; i++) { slist2.AddFast(randomData[i]); } found = slist2.IsStored("aaa"); stop = clock(); cout << "Modified sort/search required " << stop-start << " milliseconds" << endl;... using random 20-letter words: List size: 1000 Simple w/ words: 1623 Modified w/ words: 390 Simple w/ pointers: 1132 Modified w/ pointers: 100 List size: 2000 Simple w/ words: 6650 Modified w/ words: 841 Simple w/ pointers: 4556 Modified w/ pointers: 231

22 With great power… when you dynamically allocate memory using new, you are circumventing the standard memory management of C++  you must explicitly delete any memory you new e.g., if we added a Remove method to List & SortedList, must delete space void Foo() { int * ptr = new int; *ptr = 876;... delete ptr; } pointers are statically allocated values – when lifetime ends, memory for pointer is reclaimed delete reclaims the dynamic memory, not the pointer void Foo() { SortedList words; words.Add("foo"); words.Add("bar"); words.Add("biz");... } if a class object contains dynamically allocated memory, how/when does it get reclaimed?

23 Destructor classes with dynamic memory require an additional member function called a destructor (the antithesis of a constructor )  a destructor has the same name as the class, only preceded with ~  it is automatically called when the lifetime of a class object ends  should contain code for reclaiming dynamically allocated memory to avoid leakage ~List () // destructor: deletes any remaining items // (automatically called when the lifetime // of the List item ends) { for (int i = 0; i < items.size(); i++) { delete items[i]; } items.clear(); //not nec., but OK } with a derived class, the destructor for that class (if any) is called first, then the destructor for the parent class (if any)  SortedList doesn't need a destructor since the List destructor does it all!

24 But wait, there's more… there are times when you want to make a copy of an object  value parameters  assignments by default, an object is copied bit-by-bit int x = 5; int copy; copy = x; SortedList words; SortedList copy; copy = words; 5 x 5 copy "foo" "bar" "biz" "baz" "boo" "zoo" what happens? problems? isSorted = true

25 Copy constructor by default, if you copy a "dynamic" object, you only copy the pointers  both structures point to the same memory  if one alters the contents, it affects the other!  if one reaches end of lifetime, its destructor will destroy the other one's data! a copy constructor is a constructor that takes another object of the same type as argument, and creates a new copy List (const List & other) // copy constructor, creates a copy of other { items.clear(); for (int i = 0; i < other.items.size(); i++) { Add(*(other.items[i])); } SortedList (const SortedList & other) : List (other) { isSorted = other.isSorted; } note: SortedList copy constructor first calls List copy constructor, then copies isSorted value

26 Assignment operator copy constructor works for copies related to value parameters, construction to handle assignments, must overload the = operator to work for Lists  similar to copy constructor, but must return reference to new value List & operator=(const List & other) // assignment constructor, creates a copy of other { if (this != &other) { items.clear(); for (int i = 0; i < other.items.size(); i++) { Add(*(other.items[i])); } return *this; } SortedList & operator=(const SortedList & other) { if (this != &other) { List ::operator=(other); isSorted = other.isSorted; } return *this; } also, must be careful in the case where x = x;

27 Dynamic memory summary dynamic memory adds great flexibility to code  can allocate new memory on demand, resize vectors, avoid swapping data, … when you utilize dynamic memory, you are responsible for its deallocation and making sure copies/assignments are handled correctly when implementing a class that utilizes dynamic memory, generally need:  destructor:to automatically reclaim dynamic memory when the object's lifetime ends  copy constructor:to construct copies (e.g., for value parameters)  assignment operator:to handle assignments correctly