Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.

Slides:



Advertisements
Similar presentations
Pointer applications. Arrays and pointers Name of an array is a pointer constant to the first element whose value cannot be changed Address and name refer.
Advertisements

Pointers Typedef Pointer Arithmetic Pointers and Arrays.
Informática II Prof. Dr. Gustavo Patiño MJ
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.
A RRAYS, P OINTERS AND R EFERENCES 1. A RRAYS OF O BJECTS Arrays of objects of class can be declared just like other variables. class A{ … }; A ob[4];
This set of notes is adapted from that provided by “Computer Science – A Structured Programming Approach Using C++”, B.A. Forouzan & R.F. Gilberg, Thomson.
Memory Arrangement Memory is arrange in a sequence of addressable units (usually bytes) –sizeof( ) return the number of units it takes to store a type.
Pointers. Addresses in Memory When a variable is declared, enough memory to hold a value of that type is allocated for it at an unused memory location.
Pointers and Dynamic Variables. Objectives on completion of this topic, students should be able to: Correctly allocate data dynamically * Use the new.
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.
Memory and C++ Pointers.  C++ objects and memory  C++ primitive types and memory  Note: “primitive types” = int, long, float, double, char, … January.
1 CSE 303 Lecture 11 Heap memory allocation ( malloc, free ) reading: Programming in C Ch. 11, 17 slides created by Marty Stepp
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
1 Chapter 9 Pointers. 2 Topics 8.1 Getting the Address of a Variable 8.2 Pointer Variables 8.3 Relationship Between Arrays and Pointers 8.4 Pointer Arithmetic.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
Pointer Data Type and Pointer Variables
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
C++ Pointers Copies from SEE C++ programming course and from Starting Out with C++: Early Objects, 8/E by Tony Gaddis, Judy Walters and Godfrey Muganda.
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
Addresses in Memory When a variable is declared, enough memory to hold a value of that type is allocated for it at an unused memory location. This is.
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
This set of notes is adapted from that provided by “Computer Science – A Structured Programming Approach Using C++”, B.A. Forouzan & R.F. Gilberg, Thomson.
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.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 13: Pointers You are not responsible for virtual functions (starting on.
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
CPSC 252 Dynamic Memory Allocation Page 1 Dynamic memory allocation Our first IntVector class has some serious limitations the capacity is fixed at MAX_SIZE.
1 Dynamic Memory Allocation –The need –malloc/free –Memory Leaks –Dangling Pointers and Garbage Collection Today’s Material.
Dynamic Memory Allocation. Domain A subset of the total domain name space. A domain represents a level of the hierarchy in the Domain Name Space, and.
Object-Oriented Programming in C++
Pointers in C++. 7a-2 Pointers "pointer" is a basic type like int or double value of a pointer variable contains the location, or address in memory, of.
1 CS 132 Spring 2008 Chapter 3 Pointers and Array-Based Lists read p
Pointers and Dynamic Memory Allocation. Declaring a pointer.
Prachi A. Joshi Assistant Professor in CSE DIEMS,Aurangabad Unit 1 : Basic Concepts Pointers and dynamic memory allocation, Algorithm Specification, Data.
Pointers: Basics. 2 What is a pointer? First of all, it is a variable, just like other variables you studied  So it has type, storage etc. Difference:
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
Review 1 List Data Structure List operations List Implementation Array Linked List.
© Janice Regan, CMPT 128, February CMPT 128: Introduction to Computing Science for Engineering Students Pointers.
Lecture – Pointers1 C++ Pointers Joseph Spring/Bob Dickerson School of Computer Science Operating Systems and Computer Networks Based on notes by Bob Dickerson.
1 Lecture07: Memory Model 5/2/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
Dynamic Memory Management & Static Class Members Lecture No 7 Object Oriented Programming COMSATS Institute of Information Technology.
CSC Pointers Powerful feature of the C++ language One of the most difficult to master Essential for construction of interesting data structures.
C++ for Engineers and Scientists Second Edition Chapter 12 Pointers.
Pointers Lecture: 5. Topics 1 Pointers and the Address Operator 2 Pointer Variables 3 The Relationship Between Arrays and Pointers 4 Pointer Arithmetic.
Pointers: Basics. 2 Address vs. Value Each memory cell has an address associated with it
Windows Programming Lecture 03. Pointers and Arrays.
Pointers and Dynamic Memory Allocation
Yan Shi CS/SE2630 Lecture Notes
Dynamic Storage Allocation
CMSC 341 Lecture 2 – Dynamic Memory and Pointers (Review)
EGR 2261 Unit 11 Pointers and Dynamic Variables
Pointers.
Pointers Revisited What is variable address, name, value?
Chapter 10: Pointers Starting Out with C++ Early Objects Ninth Edition
Dynamically Allocated Memory
Dynamic Memory Allocation
Object Oriented Programming COP3330 / CGS5409
Chapter 15 Pointers, Dynamic Data, and Reference Types
Pointers, Dynamic Data, and Reference Types
Chapter 15 Pointers, Dynamic Data, and Reference Types
Dynamic Memory.
Pointers and References
Pointers, Dynamic Data, and Reference Types
SPL – PS2 C++ Memory Handling.
Presentation transcript:

Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes

2 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long double

What is reference?  simple data type: reference operator &  the address of a variable of certain data type int num = 10; int &rNum = num;  Do you remember? —an array or object must be passed as a reference parameter int nums[10]; Student stu; StudentList stuList; … avg = Average(nums); stuList.Add(stu);  Once a reference is created, it cannot be later made to refer another variable/object; it cannot be reseated. int Average( const int myArray[] ); void Add( const Student& stu );

What is a pointer variable?  A pointer variable is a variable whose value is the address of a location in memory.  Unlike a reference variable, a pointer can redirect to other locations later.  To declare a pointer variable, you must specify the type of value that the pointer will point to. int *p; // p will hold the address of an int char *q; // q will hold the address of a char int a, *b; // * is paired with the identifier. // In this case, we have a int variable a and // a pointer of int type b

For a normal variable  int num; MemoryAddressidentifier ? num 0010

For a normal variable  int num;  num = 50; MemoryAddressidentifier num 0010

Pointer  int num;  num = 50;  int *p; MemoryAddressidentifier num 0010 ? p 0012 A pointer variable contains the memory address of another variable.

Pointer  int num;  num = 50;  int *p;  p = # MemoryAddressidentifier num 0010 p 0012 & is the reference(address-of )operator.

Pointer  int num;  num = 50;  int *p;  p = &num;  cout << *p; MemoryAddressidentifier num 0010 (*) here is the dereference operator. *p is used to access the place p points to.  you will see 50 on the screen p 0012

Pointer  int num;  num = 50;  int *p;  p = &num;  cout << *p;  *p = 100; MemoryAddressidentifier num 0010 change the value at the address p points to p 0012 //direct addressing //indirect addressing

char ch; ch = ‘A’; char* q; q = &ch; *q = ‘Z’; char* p; p = q; // the right side has value 4000 // now p and q both point to ch Another Example 4000 A Z ch q p

NULL pointer  Use NULL to initialize pointers that don’t currently point to anything. —used to initialize pointers —can be converted to pointers of any type — int *p = NULL; It is an error to dereference a pointer whose value is NULL. It is the programmer’s job to check for this.

Dynamic Memory Allocation  In the previous example, memory space for num and p are statically allocated —at compile time —from stack memory (activation record and global variables)  Dynamic memory allocation —at run time —from heap memory (free store: dynamic)  In java, all user-defined types are allocated from heap  In C++, use new operator to get data from heap

Dynamic Memory Allocation  int *p = new int; MemoryAddressidentifier p 0010

Dynamic Memory Allocation  int *p = new int; MemoryAddressidentifier ? p 0010 unnamed dynamically allocated integer variable (from heap) 0080

Dynamic Memory Allocation  int *p = new int;  With Initialization:  int *p = new int(99); MemoryAddressidentifier ? p The dynamically allocated variable can only be indirectly addressed through the pointer returned by new. unnamed dynamically allocated integer variable (from heap)

What does new do?  It takes a pointer variable,  allocates heap memory for it to point, and  leaves the address of the assigned memory in the pointer variable.  If there is no more memory, the pointer variable is set to NULL.

Dynamic Array  Using new, now we can dynamically decide the size of an array. int size; cin >> size; char *text = new char[size];

Pointers and Arrays  C++ arrays are not objects as in Java. They are really just pointers! char name[30]; // name is actually &name[0] char *np; np = &name[0]; // same as np = name;  C++ allows pointer arithmetic: … cin >> *np; while( *np != ‘/n’ ) { np++; cin >> *np; }  name is a constant pointer. name[i] is the same as *(name + i) // hope that all names are // shorter than 30 characters // moves np ahead sizeof(char) bytes // and points to the next element.

Pointers and Objects  How to declare an object? Student stu(…); OR Student *stu = new Student(…);  For the second declaration, we can make a public method call like this: stu->GetGPA(); // stu is a Student object // located at the stack memory // stu is a pointer of Student type // located at the heap memory // This is the same as // (*stu).GetGPA();

Pointers and Objects  We can make a dynamic array of objects: Student * stuList = new Student[n];  In this case, Student must have a default constructor!  An alternative is to make a dynamic array of Student pointers Student **stuList = new Student*[n];  In this case, no default constructor is needed, but memory management becomes more complicated.

Memory Leak  Memory is allocated but not released  causing an application to consume memory  reducing the available memory for other applications and  eventually causing the system to page virtual memory to the hard drive  slowing the application or crashing the application when the computer memory resource limits are reached. Example: int *p1 = new int; int *p2 = new int(99); *p1 = 10; p2 = p1; // The memory cell p2 originally // points at now can no longer be // accessed  this is called garbage.

Deallocate Memory: delete  delete operator is used to return to the heap a memory location allocated previously by the new operator.  A pointer p is pointing to a dynamically allocated space. When to delete p ? — p is about to point to another space; —right before the program exit. int *p1 = new int; int *p2 = new int(99); *p1 = 10; delete p2; // This prevents memory leak. p2 = p1; … int *a = new int(n); … delete[] a; // deallocate the entire array space.

Enable Memory Leak Detection  Visual Studio provides C Run-Time Libraries (CRT) debug heap functions. To enable:  include in the exact order.  add _CrtDumpMemoryLeaks(); immediately before the program exit.  When you run your program under the debugger, _CrtDumpMemoryLeaks displays memory leak information in the Output window. #define _CRTDBG_MAP_ALLOC #include

Dangling Pointer  Pointers that do not point to a valid object. —Dangling pointers arise when an object is deleted or deallocated, without modifying the value of the pointer, so that the pointer still points to the memory location of the deallocated memory. —If later the program dereferences the (now) dangling pointer, unpredictable behavior may result.  That is why Java introduced automatic garbage collection!

Dangling Pointer Example 8 ptr -5 ptr2 int* ptr = new int; *ptr = 8; int* ptr2 = new int; *ptr2 = -5; ptr = ptr2; 8 cannot be addressed and thus become a garbage

Dangling Pointer Example int* ptr = new int; *ptr = 8; int* ptr2 = new int; *ptr2 = -5; ptr = ptr2; delete ptr2; // ptr is left dangling ptr2 = NULL; 8 ptr NULL ptr2

Dangling Pointer Example  common mistake: returning address of local data  Both create dangling pointers! —xyz will be deleted after the function call —returned pointer will be pointing to empty slot. X* foo() { X xyz;... operate on xyz... return &xyz; } char* g() { char str[100];... operate on str... return str; }