2. pointer

Download 2. Pointer

Post on 22-Feb-2016




0 download

Embed Size (px)


2. Pointer. Yan Shi CS/SE2630 Lecture Notes. floating. address. float double long double. pointer reference. C++ Data Types. simple. structured. integral enum. array struct union class. char short int long bool. What is reference?. simple data type - PowerPoint PPT Presentation


2. Pointer

2. PointerYan ShiCS/SE2630 Lecture NotesComputer Science and Software EngineeringUniversity of Wisconsin - Platteville2C++ Data Typesstructuredarray struct union class addresspointer referencesimple integral enumchar short int long boolfloatingfloat double long double2What 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 bereseated.int Average( const int myArray[] );

void Add( const Student& stu );3What 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 b4For a normal variableint num;......MemoryAddressidentifier...?num0010For a normal variableint num;num = 50;......MemoryAddressidentifier...50num0010Pointerint num;num = 50;int *p;......MemoryAddressidentifier...50num0010?p0012A pointer variable contains the memory address of another variable.Pointerint num;num = 50;int *p;p = # ......MemoryAddressidentifier...50num00100010p0012& is the reference(address-of )operator.Pointerint num;num = 50;int *p;p = #cout size;char *text = new char[size];Pointers and ArraysC++ 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 ObjectsHow to declare an object?Student stu(); ORStudent *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 ObjectsWe 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 pointersStudent **stuList = new Student*[n];In this case, no default constructor is needed, but memory management becomes more complicated.Memory LeakMemory 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 DetectionVisual 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 #include By including crtdbg.h, you map themallocandfreefunctions to their debug versions,_malloc_dbgand_free_dbg, which keep track of memory allocation and deallocation. This mapping occurs only in a debug build (in which_DEBUGis defined). Release builds use the ordinarymallocandfreefunctions.

The#definestatement maps the base versions of the CRT heap functions to the corresponding debug versions. You do not absolutely need this statement, but without it, the memory leak dump will contain less useful information.

24Dangling PointerPointers 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




int* ptr = new int; *ptr = 8; int* ptr2 = new int; *ptr2 = -5; ptr = ptr2; 8 cannot be addressed and thus become a garbageDangling Pointer Exampleint* ptr = new int; *ptr = 8; int* ptr2 = new int; *ptr2 = -5; ptr = ptr2;

delete ptr2;// ptr is left dangling ptr2 = NULL; 8



ptr2 Dangling Pointer Examplecommon mistake: returning address of local data

Both create dangling pointers!xyz will be deleted after the function callreturned 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; }