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

Similar documents
Linked Memory. Pointers Linked Lists. January 19, 2018 Cinda Heeren / Geoffrey Tien 1

Pointers. September 13, 2017 Hassan Khosravi / Geoffrey Tien 1

APSC 160 Review Part 2

Dynamic Memory. Dynamic Memory Allocation Strings. September 18, 2017 Hassan Khosravi / Geoffrey Tien 1

Memory and C++ Pointers

C++ Object-Oriented Programming

Pointers II. Class 31

Abstract Data Types. Stack. January 26, 2018 Cinda Heeren / Geoffrey Tien 1

Arrays. Returning arrays Pointers Dynamic arrays Smart pointers Vectors

Queues. ADT description Implementations. October 03, 2017 Cinda Heeren / Geoffrey Tien 1

Variables, Memory and Pointers

FORM 2 (Please put your name and form # on the scantron!!!!)

内存管理. Memory management

Homework #3 CS2255 Fall 2012

Exam 3 Chapters 7 & 9

Tree traversals. Review: recursion Tree traversals. October 05, 2017 Cinda Heeren / Geoffrey Tien 1

[0569] p 0318 garbage

Data Structure Series

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

CS201- Introduction to Programming Current Quizzes

Memory, Arrays, and Parameters

In Java we have the keyword null, which is the value of an uninitialized reference type

Arrays and Linked Lists

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

Trees. Introduction & Terminology. February 05, 2018 Cinda Heeren / Geoffrey Tien 1

CS 103 Unit 11. Linked Lists. Mark Redekopp

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

Pointers. Memory. void foo() { }//return

Separate Compilation Model

Variation of Pointers

CMSC 341 Lecture 2 Dynamic Memory and Pointers

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

Pointers Ch 9, 11.3 & 13.1

! A pointer variable (or pointer): ! An asterisk is used to define a pointer variable. ! ptr is a pointer to an int or

Pointers, Dynamic Data, and Reference Types

School of Science and Technology

a data type is Types

Recursion. February 02, 2018 Cinda Heeren / Geoffrey Tien 1

Pointers (part 1) What are pointers? EECS We have seen pointers before. scanf( %f, &inches );! 25 September 2017

cout << "How many numbers would you like to type? "; cin >> memsize; p = new int[memsize];

04-17 Discussion Notes

C11: Garbage Collection and Constructors

CS101: Fundamentals of Computer Programming. Dr. Tejada www-bcf.usc.edu/~stejada Week 8: Dynamic Memory Allocation

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

Dynamic Memory Allocation

Pointers. 1 Background. 1.1 Variables and Memory. 1.2 Motivating Pointers Massachusetts Institute of Technology

FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each):

Pointers and References

CPSC 427a: Object-Oriented Programming

INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS

CS 103 Unit 11. Linked Lists. Mark Redekopp

CS 161 Exam II Winter 2018 FORM 1

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

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

Chapter 2. Procedural Programming

C10: Garbage Collection and Constructors

Queue ADT. January 31, 2018 Cinda Heeren / Geoffrey Tien 1

BITG 1113: POINTER LECTURE 12

Programming Abstractions

Object-Oriented Principles and Practice / C++

Dynamic Data Structures

Dynamic Allocation of Memory

Arrays and Pointers. CSE 2031 Fall November 11, 2013

CSCI-1200 Data Structures Spring 2018 Lecture 7 Order Notation & Basic Recursion

Scott Gibson. Pointers & Dynamic Memory. Pre & Co Requisites. Random Access Memory. Data Types. Atomic Type Sizes

CSC1322 Object-Oriented Programming Concepts

COMP 524 Spring 2018 Midterm Thursday, March 1

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

+ Abstract Data Types

Chapter 10 Pointers and Dynamic Arrays. GEDB030 Computer Programming for Engineers Fall 2017 Euiseong Seo

DYNAMIC ARRAYS; FUNCTIONS & POINTERS; SHALLOW VS DEEP COPY

CS 137 Part 5. Pointers, Arrays, Malloc, Variable Sized Arrays, Vectors. October 25th, 2017

CSE 333 Midterm Exam 7/27/15 Sample Solution

Darshan Institute of Engineering & Technology for Diploma studies Unit 4

Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example

Lecture 15a Persistent Memory & Shared Pointers

Arrays and Pointers. Arrays. Arrays: Example. Arrays: Definition and Access. Arrays Stored in Memory. Initialization. EECS 2031 Fall 2014.

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

Manual Allocation. CS 1622: Garbage Collection. Example 1. Memory Leaks. Example 3. Example 2 11/26/2012. Jonathan Misurda

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

Pointers and Terminal Control

FOR Loop. FOR Loop has three parts:initialization,condition,increment. Syntax. for(initialization;condition;increment){ body;

CS24 Week 3 Lecture 1

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

Pointers review. int a = 5; int *ptr = &a; cout << *ptr;

CS31 Discussion. Jie(Jay) Wang Week8 Nov.18

[CSE10200] Programming Basis ( 프로그래밍기초 ) Chapter 9. Seungkyu Lee. Assistant Professor, Dept. of Computer Engineering Kyung Hee University

Answer: Early binding generally leads to greater efficiency (compilation approach) Late binding general leads to greater flexibility

Arrays and functions Multidimensional arrays Sorting and algorithm efficiency

Chapter-11 POINTERS. Important 3 Marks. Introduction: Memory Utilization of Pointer: Pointer:

Implementing an ADT with a Class

CSE 333 Midterm Exam 7/29/13

CS 11 C track: lecture 5

Lecture on pointers, references, and arrays and vectors

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

ADT: Design & Implementation

CS201 Latest Solved MCQs

(13-2) Dynamic Data Structures I H&K Chapter 13. Instructor - Andrew S. O Fallon CptS 121 (November 17, 2017) Washington State University

Chapter 10. Pointers and Dynamic Arrays. Copyright 2016 Pearson, Inc. All rights reserved.

CISC220 Lab 2: Due Wed, Sep 26 at Midnight (110 pts)

Transcription:

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

Releasing Dynamic Memory When a function call is complete its stack memory is released and can be re-used Dynamic memory should also be released Failing to do so results in a memory leak It is sometimes not easy to determine when dynamic memory should be released Data might be referred to by more than one pointer Memory should only be released when it is no longer referenced by any pointer Rule of thumb: if you new something, you should delete it (eventually) September 21, 2017 Cinda Heeren / Geoffrey Tien 2

Stack memory VS heap memory Stack fast access allocation/deallocation and space automatically managed memory will not become fragmented Heap variables accessible outside declaration scope no (practical) limit on memory size variables can be resized local variables only limit on stack size (OSdependent) variables cannot be resized (relatively) slower access no guaranteed efficient use of space memory management is programmer's responsibility September 21, 2017 Cinda Heeren / Geoffrey Tien 3

Addresses and pointers Every storage location in memory (RAM) has an address associated with it The address is the location in memory where a given variable or identifier stores its data Can think of address in memory like a mailbox number Use the address to find where the mailbox is Look inside the mailbox to access the contents/value A pointer is a special type of variable That stores an address rather than a value The address is used to find a value elsewhere in memory September 21, 2017 Cinda Heeren / Geoffrey Tien 4

Declaring pointers Pointer variables are declared as follows: datatype* identifier e.g. int* ptr; or int * ptr; or int *ptr; Note that the type of a pointer is not the same as the type it points to e.g. ptr is a pointer to an int, but is itself not an int Warning! The declaration int* var1, var2; declares var1 as a pointer, but var2 as an integer! To declare both as pointers, either declare individually, or: int *var1, *var2; September 21, 2017 Cinda Heeren / Geoffrey Tien 5

Address operator and dereferencing Pointers can be assigned the address of an existing variable Using the address operator, & The value which a pointer points to can be accessed by dereferencing the pointer Using the * operator p x 4096 23 47 38 0 1 2 12 2 20-1 int x = 23; int* p = &x; x = 47; *p = 38; September 21, 2017 Cinda Heeren / Geoffrey Tien 6

Pointers as parameters Passing pointer parameters allows the function to access and/or modify the actual parameter int getarraysum(int arr[], int size, int* pcount) { int sum = 0; for (int i = 0; i < size; i++) { if (arr[i] > 0) (*pcount)++; sum += arr[i]; } return sum; } int numpositive = 0; int numbers[] = {3, 7, -9, 5, -4}; int result = getarraysum(numbers, 5, &numpositive); cout << "Array sum: " << result << endl; cout << "Number of positive elements: " << numpositive << endl; September 21, 2017 Cinda Heeren / Geoffrey Tien 7

Pointers as parameters Another example void f1(int arg) { arg = 22; printf("f1 arg: %d\n", arg); } void f2(int* arg) { *arg = 410; printf("f2 arg: %d\n", arg); } int x = 45; f1(x); printf("x after f1: %d\n", x); f2(&x); printf("x after f2: %d\n", x); September 21, 2017 Cinda Heeren / Geoffrey Tien 8

Pointer to a pointer...to a pointer to a pointer... int main() { int x = 5; int* p = &x; *p = 6; int** q = &p; int*** r = &q; } cout << "*p: " << *p << endl; cout << "*q: " << *q << endl; cout << "**q: " << *(*q) << endl; "You can keep adding levels of pointers until your brain explodes or the compiler melts whichever happens soonest" stackoverflow user JeremyP September 21, 2017 Cinda Heeren / Geoffrey Tien 9

Pointers and dynamic memory The new keyword allocates space in dynamic memory and returns the first address of the allocated space delete releases the memory at the address referenced by its pointer variable delete[] is used to release memory allocated to array variables int a = 5; int* b = new int; int* c = &a; *c = 4; int** d = &b; int* e = new int[a]; **d = 3; int* f = new int[*b]; delete b; delete e; // causes a memory leak delete[] f; September 21, 2017 Cinda Heeren / Geoffrey Tien 10

Dynamic allocation of a 2D array int dim_row = 3; int dim_col = 5; int** myarray; // pointer to a pointer stack heap myarray September 21, 2017 Cinda Heeren / Geoffrey Tien 11

Linked Lists September 21, 2017 Cinda Heeren / Geoffrey Tien 12

Linked lists Imagine an array partially filled with data And we want to insert an item in a particular position in the middle 17 A motivation 12 15 16 19 22 28 34 37 41 46 All of these elements must be shifted over one at a time Linked lists are a dynamic data structure that can achieve fast insertions/ deletions in the middle September 21, 2017 Cinda Heeren / Geoffrey Tien 13

Linked list nodes A linked list is a dynamic data structure that consists of nodes linked together A node is a data structure that contains data the location of the next node September 21, 2017 Cinda Heeren / Geoffrey Tien 14

Node pointers A node contains the address of the next node in the list In C++ this is recorded as a pointer to a node Nodes are created in dynamic memory And their memory locations are not in sequence The data attribute of a node varies depending on what the node is intended to store September 21, 2017 Cinda Heeren / Geoffrey Tien 15

Linked lists A linked list is a chain of nodes where each node stores the address of the next node Start 7 2 6 8 This symbol indicates a null pointer September 21, 2017 Cinda Heeren / Geoffrey Tien 16

Linked list implementation Node class class Node { public: int data; Node* next; }; next points to another node, hence its type Node* attributes / members of a particular node can be accessed using the '.' (dot) operator or the '->' (arrow) operator as a shorthand for pointer types equivalent to dereferencing and using dot operator Node nd; nd.data = 5; Node* p = nd.next; (*p).data = 5; Node* q = *((*p).next).next; Node* r = q->next->next; September 21, 2017 Cinda Heeren / Geoffrey Tien 17

Building a linked list Node* a = new Node(7, null); Assume we have written a parameterized constructor for the Node class a 7 September 21, 2017 Cinda Heeren / Geoffrey Tien 18

Building a linked list Node* a = new Node(7, null); a->next = new Node(3, null); a 7 3 September 21, 2017 Cinda Heeren / Geoffrey Tien 19

Traversing a linked list Node* a = new Node(7, null); a->next = new Node(3, null); Node* p = a; p = p->next; // go to next node p = p->next; a 7 3 p September 21, 2017 Cinda Heeren / Geoffrey Tien 20

Linked list insertion Insertion in a singly-linked list requires only updating the next node reference of the preceding position a 15 16 19 22 28 p 17 b Node* b = new Node(17, p->next); p->next = b; Now think about how we might use a linked list as the data structure for implementing the Stack ADT September 21, 2017 Cinda Heeren / Geoffrey Tien 21

Linked list removal Likewise, we can remove a node by updating the pointer of the preceding node but remember to delete the removed node! a 15 16 19 22 28 p b p->next = b->next; delete b; September 21, 2017 Cinda Heeren / Geoffrey Tien 22

Readings for this lesson Koffman Chapters P.5, 4.5 Next class: Koffman Chapter 5 (ADT Stack) September 21, 2017 Cinda Heeren / Geoffrey Tien 23