CMSC 202. Pointers Dynamic Memory Allocation

Similar documents
CS201- Introduction to Programming Current Quizzes

3/22/2016. Pointer Basics. What is a pointer? C Language III. CMSC 313 Sections 01, 02. pointer = memory address + type

10/20/2015. Midterm Topic Review. Pointer Basics. C Language III. CMSC 313 Sections 01, 02. Adapted from Richard Chang, CMSC 313 Spring 2013

C++ for Java Programmers

CSCI 2212: Intermediate Programming / C Review, Chapters 10 and 11

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

Section Notes - Week 1 (9/17)

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 13, SPRING 2013

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

Review: C Strings. A string in C is just an array of characters. Lecture #4 C Strings, Arrays, & Malloc

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

C++ ARRAYS POINTERS POINTER ARITHMETIC. Problem Solving with Computers-I

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

How to declare an array in C?

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

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

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 13, FALL 2012

CS162 - POINTERS. Lecture: Pointers and Dynamic Memory

Programming in C. Pointers and Arrays

CSCI-1200 Data Structures Fall 2017 Lecture 5 Pointers, Arrays, & Pointer Arithmetic

Pointers. A pointer value is the address of the first byte of the pointed object in the memory. A pointer does not know how many bytes it points to.

An array is a collection of data that holds fixed number of values of same type. It is also known as a set. An array is a data type.

Pointers and Arrays 1

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

Intermediate Programming, Spring 2017*

CSE 333 Midterm Exam 5/10/13

Cpt S 122 Data Structures. Course Review Midterm Exam # 1

Student Number: Computer Science 211b Final Examination. 28 April hours

2. dead code elimination (declaration and initialization of z) 3. common subexpression elimination (temp1 = j + g + h)

Algorithms & Data Structures

First of all, it is a variable, just like other variables you studied

REFERENCES, POINTERS AND STRUCTS

Lecture Notes on Queues

NEXT SET OF SLIDES FROM DENNIS FREY S FALL 2011 CMSC313.

Data Representation and Storage

CSE 413 Midterm, May 6, 2011 Sample Solution Page 1 of 8

CSE 333 Midterm Exam Sample Solution 5/10/13

Data and File Structures Laboratory

Introduction to C++ Introduction. Structure of a C++ Program. Structure of a C++ Program. C++ widely-used general-purpose programming language

Pointer Data Type and Pointer Variables

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

CS 31: Intro to Systems Arrays, Structs, Strings, and Pointers. Kevin Webb Swarthmore College March 1, 2016

COS 140: Foundations of Computer Science

Introduction to C++ with content from

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

CSE 230 Intermediate Programming in C and C++ Arrays and Pointers

ECE 2035 A Programming Hw/Sw Systems Fall problems, 8 pages Final Exam 8 December 2014

CMSC202 Computer Science II for Majors

Computer Programming

CSE 333 Midterm Exam 5/9/14 Sample Solution

Pointer Declarations

Chapter 6: Using Arrays

CSCI-1200 Data Structures Fall 2012 Lecture 5 Pointers, Arrays, Pointer Arithmetic

Organization of Programming Languages CS320/520N. Lecture 06. Razvan C. Bunescu School of Electrical Engineering and Computer Science

Pointers. Addresses in Memory. Exam 1 on July 18, :00-11:40am

DYNAMIC ARRAYS; FUNCTIONS & POINTERS; SHALLOW VS DEEP COPY

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #34. Function with pointer Argument

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

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #33 Pointer Arithmetic

Computer Science & Engineering 150A Problem Solving Using Computers

Chapter 9. Pointers and Dynamic Arrays

Cpt S 122 Data Structures. Data Structures

OCA Java SE 7 Programmer I Certification Guide By Mela Gupta. Arrays

Course Text. Course Description. Course Objectives. StraighterLine Introduction to Programming in C++

Type Checking. Prof. James L. Frankel Harvard University

Data Types (cont.) Subset. subtype in Ada. Powerset. set of in Pascal. implementations. CSE 3302 Programming Languages 10/1/2007

ECE 2035 Programming HW/SW Systems Fall problems, 5 pages Exam Three 28 November 2012

Homework #3 CS2255 Fall 2012

Chapter 9 Introduction to Arrays. Fundamentals of Java

APS105. Malloc and 2D Arrays. Textbook Chapters 6.4, Datatype Size

Dynamic Data Structures. CSCI 112: Programming in C

CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Pointers, Dynamic Data, and Reference Types

EE 472: Pointers. 1 Memory Addresses and Pointers. James Peckol and Blake Hannaford Department of Electrical Engineering The University of Washington

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

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

WHAT POINTERS REALLY ARE

! Determine if a number is odd or even. ! Determine if a number/character is in a range. - 1 to 10 (inclusive) - between a and z (inclusive)

Chapter 9: Pointers Co C pyr py igh i t gh Pear ea so s n n E ducat ca io i n, n Inc. n c.

Pointers Pointer Variables. Pointer Variables Getting the Address of a Variable. Each variable in program is stored at a

Lecture Notes on Memory Layout

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

CS 161 Exam II Winter 2018 FORM 1

CS2351 Data Structures. Lecture 7: A Brief Review of Pointers in C

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

BBM 201 DATA STRUCTURES

Character Strings. String-copy Example

Arrays, Pointers and Memory Management

[0569] p 0318 garbage

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

CSCI-1200 Data Structures Spring 2014 Lecture 5 Pointers, Arrays, Pointer Arithmetic

C++ PROGRAMMING LANGUAGE: DYNAMIC MEMORY ALLOCATION AND EXCEPTION IN C++. CAAM 519, CHAPTER 15

CSCI-1200 Data Structures Fall 2018 Lecture 5 Pointers, Arrays, & Pointer Arithmetic

Declaring Pointers. Declaration of pointers <type> *variable <type> *variable = initial-value Examples:

Lecture 10 Notes Linked Lists

Data Representation and Storage. Some definitions (in C)

Pointers Ch 9, 11.3 & 13.1

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING PREVIEW SLIDES 14, SPRING 2013

More about BOOLEAN issues

Transcription:

CMSC 202 Pointers Dynamic Memory Allocation 1

A simple variable A variable is drawn as a labeled box int x; X : 2

Complex Variables A complex variable is drawn as complex boxes (horizontal for array, vertical for struct) struct Astruct { int y; char c; }; int intarray [ 4 ]; Astruct mystruct; intarray: mystruct : 3

Pointer value A pointer value is drawn as an arrow. The arrow points to a picture of the object to which the pointer points. The pointer is said to reference the object. 3 4

Pointer Variable A pointer variable is drawn as a labeled box, like any other simple variable int *iptr; iptr: NULL is a pointer value that doesn t point to anything and is drawn as a box with a slash 5

When a pointer variable points to an object the base of the arrow representing the pointer value is placed in the pointer variable s box iptr : 42 6

Assignment to pointer variables A pointer variable receives a value through assignment. Newly allocated space (using new) Previously allocated space 7

Allocating space with new Graphically depict the result of allocating memory with new by 1. Figure out what kind of space is being allocated 2. Draw a box to represent the allocated space 3. Draw an arrow pointing to the new box and place it s base in the box representing the pointer variable being assigned to 8

A new picture class Car { public:.... private: string m_color; int m_mileage; }; CarPtr m_color m_mileage Car *CarPtr; CarPtr = new Car; 9

What s in the new data? Nothing Conceptually, after you use new, you get some blank space to fill with data Something Your new space is not initialized to some zero value. Try allocating some new memory with new and immediately printing its contents. You will see all sorts of random values. This is related to a security concern we will discuss later. 10

Pointer Assignment Suppose thing1 and thing2 are pointers to int and thing1 points to an int whose value is 17. thing1: 17 thing2: 11

Pointer Assignment (cont d) And now execute the statement thing2 = thing1; 1. Draw a new arrow that points to the box being referenced by the pointer value on the right hand side 2. Place the the base of the new arrow in the box representing the pointer variable on the left hand side 17 thing1: thing2: 12

Dereferencing pointers Given the following picture thing1: 17 The * (star) operator deferences a pointer variable. In terms of our picture it means follow the arrow. We can use dereferencing to change what a pointer value points to: *thing1 = 42; results in this picture thing1: 42 13

An exercise for the student Given the following declarations and code typedef int* intptrarray [ 3 ]; typedef intptrarray* arrayptr; arrayptr cat; int *dog; dog = new int; *dog = 42; cat = new intptrarray; cat[0] = dog; cat[1] = NULL; cat[2] = new int; *(cat[2]) = 17; 14

The Questions 1. What type of variable is dog? 2. What type of variable is cat? (NO, the answer is NOT arrayptr). 3. Draw the picture that results from the code 15

The & operator The & (address of) operator is used to create an arrow that points to an existing box. Consider the following code int value; int *pvalue; value = 17; pvalue = &value; value: pvalue: 17 The expression &value gives us a pointer to value 16

Pointers and Arrays A strong relationship between pointers and arrays. The name of an array is defined to be a pointer to the the first (0 th ) element of the array Consider the declaration int bongo [ 4 ]; The name bongo can be used as a pointer to reference bongo[0]. *bongo = 42; is equivalent to bongo[0] = 42; 17

Pointers to array elements foo: foo + 1 bar: 0 1 2 3 4 5 If a pointer value references a particular array element, then adding an integer, n, to that pointer value will result in a new pointer value that references the array element n elements way from the original element 18

Putting these together we observe that the nth element of an array called myarray can be referenced as myarray + n Thus, the following expressions are equivalent myarray [n] and *(myarray + n) &myarray [ n ] and myarray + n 19

Using delete delete is the operator which is used to recycle memory allocated with new The forms of new and delete must match // for a single object int * x = new int; delete x; // for an array of object int *intp = new int [ 7 ]; delete [ ] intp; 20

A delete example Suppose soup is a pointer variable that references an int containing 42 soup: 42 Then the statement delete soup recycles the space referenced by soup. soup: 42 21

A potential problem int *soup, *salad; soup = new int ( 42 ); salad = soup; delete soup; What does the picture of memory look like? What s the potential problem? 22

A potential security problem Recall that newly allocated space is filled with random data. Where does that data come from? It s not truly random, but it is whatever old data was left behind when some program used delete. Your deleted data is not gone; it is floating around somewhere in the computer s memory, to be reallocated when another program needs the space. 23

A potential security problem So, what happens to the data in a credit card number when you delete it? What if some clever hacker could figure out a way to get that deleted memory reallocated to another program? To avoid this problem, any sensitive data should have its value changed (set to zero) before calling delete. 24

Multi-dimensional Arrays We declare a static 2-dimensional array as char charray1 [ 3 ] [ 4 ]; What we envision is 0 1 2 3 charray1 : 0 1 2 25

Static 2-D array in Memory What we get in memory is charray1: row 0 0 0 0 1 1 1 1 2 2 2 2 column 0 1 2 3 0 1 2 3 0 1 2 3 We use double subscripts ( charray [ 2 ] [ 1 ] ) to reference the elements by row/column. The compiler uses the row number, column number, number of columns and array type to calculate a memory address. 26

A dynamic 2-D array To dynamically allocate a 2-D array, we must create an array of pointers (the rows) in which each row element points to an array of elements (the columns). We need only declare the name of the dynamic array correctly char **charray2; 27

char **charray2 This declaration is read as charray2 is a pointer to a pointer to a char In reality, the compiler doesn t know if you plan to use charray2 to point to one pointer to char or as the name of an array of many pointers to char. When we use it for dynamic 2-D arrays, we use it to point to an array of pointers to char 28

The code // the array of pointers for the rows charray2 = new char* [ 3 ]; // now allocate the elements of each row for (int r = 0; r < 3; r++) charray2 [ r ] = new char [ 4 ]; 29

Dynamic 2-D Array in Memory charray2: 0 0 1 2 3 1 2 We can still use double subscript ( charray [ 2 ] [ 1 ] ) to access the elements. The compiler uses pointer arithmetic to find the memory address. 30

delete ing a dynamic array To deallocate a dynamically allocated multidimensional array, we must deallocate memory in the reverse order that it allocated for (int r = 0; r < 3; r++) delete [ ] charray2[ r ]; delete [ ] charray2; 31

Exercises for the student 1. Draw the results of the following code char *fischer; fischer = new char[3]; fischer[0] = p ; fischer[1] = k ; fischer[2] = 4 ; 32

More exercises 2.Draw the results of the following code struct soprano { int x; char ch[3]; }; typedef soprano* alto; soprano *jane; alto *joe; jane = new soprano; jane->x = 1; jane-> ch[ jane->x ] = G ; joe = new alto[4]; joe[0] = new soprano; joe[0]->ch[2] = Q ; joe[3] = jane; 33

Even more exercises 3. Write the typedefs, declarations and code that will create the picture below foo: 17 42 34

Still more 4. Write the typedefs, declarations and code that will produce the picture below foo: 16 bar: 16 35

And one last exercise 5. Write the typedefs, declarations and code that will produce the picture below. tom: 5 36