Download
pointers memory allocation n.
Skip this Video
Loading SlideShow in 5 Seconds..
Pointers & Memory Allocation PowerPoint Presentation
Download Presentation
Pointers & Memory Allocation

Pointers & Memory Allocation

168 Vues Download Presentation
Télécharger la présentation

Pointers & Memory Allocation

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

  1. Pointers & Memory Allocation by Briana Morrison adapted from Dale/Weems/Headington and Cahoon/Davidson

  2. Topics • Defintion and Usage of Pointers • Using the Address-Of Operator & • Declaring and Using Pointer Variables • Using the Indirection (Dereference) Operator * • The NULL Pointer • Using C++ Operators new and delete • Meaning of an Inaccessible Object • Meaning of a Dangling Pointer

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

  4. Why use Pointers • Mechanism in C++ to pass command-line parameters to a program • This feature is less important now with the use of graphical interfaces • Necessary for dynamic objects • Objects whose memory is acquired during program execution as the result of a specific request • Dynamic objects enable flexible-sized lists • Already seen as reference arguments and arrays

  5. 6000 ‘H’ ‘e’ ‘l’ ‘l’ ‘o’ ‘\0’ str [0] [1] [2] [3] [4] [5] [6] [7] Recall that . . . char str [ 8 ]; stris the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant because the value of str itself cannot be changed by assignment. It “points” to the memory location of a char.

  6. 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 the address of the variable int x; float number; char ch; 2000 2002 2006 x number ch

  7. Obtaining Memory Addresses the address of a non-array variable can be obtained by using the address-of operator & int x; float number; char ch; cout << “Address of x is “ << &x << endl; cout << “Address of number is “ << &number << endl; cout << “Address of ch is “ << &ch << endl;

  8. What is a pointer variable? • A pointer variable is a variable whose value is the address of a location in memory. • to declare a pointer variable, you must specify the type of value that the pointer will point to,for example, int* ptr;// ptr will hold the address of an int char* q;// q will hold the address of a char

  9. Basics • Pointer • Object whose value represents the location of another object • In C++ there are pointer types for each type of object • Pointers to int objects • Pointers to char objects • Pointers to Rational objects • Even pointers to pointers • Pointers to pointers to int objects

  10. Syntax • Examples of uninitialized pointers int *iPtr; // iPtr is a pointer to an int char *s; // s is a pointer to a char Rational *rPtr; // rPtr is a pointer to a Rational • Examples of initialized pointers int i = 1; char c = 'y'; int *ptr; // ptr is a pointer to an integer ptr = &i; // ptr now points to int i char *t; // t is a pointer to a character t = &c; // t now points to char c Indicates pointer object Indicates we want the address of the object

  11. Memory Depiction int i = 1; char c = 'y'; int *ptr; ptr = &i; char *t; t = &c;

  12. Using a Pointer Variable int x; x = 12; int* ptr; ptr = &x; NOTE: Because ptr holds the address of x, we say that ptr “points to” x 2000 12 x 3000 2000 ptr

  13. Indirection Operator An asterisk has two uses with regard to pointers • We have already seen that in a definition an asterisk indicates that the object being defined is a pointer char *s; // s is of type pointer to char • In expressions, an asterisk when applied to a pointer indicates that we want the object to which the pointer points int i = 1; int *ptr = &i;// ptr points to i cout << *ptr << endl;// displays 1

  14. Address Operator & use is not limited to definition initialization int i = 1; int j = 2; int *ptr; ptr = &i; // ptr points to location of i *ptr = 3; // contents of i are updated ptr = &j; // ptr points to location of j *ptr = 4; // contents of j are updated cout << i << " " << j << endl;

  15. Unary operator * is the indirection (deference) operator int x; x = 12; int* ptr; ptr = &x; cout << *ptr; NOTE: The value pointed to by ptr is denoted by *ptr 2000 12 x 3000 2000 ptr

  16. Using the Dereference Operator int x; x = 12; int* ptr; ptr = &x; *ptr = 5; // changes the value // at address ptr to 5 2000 12 x 3000 2000 ptr 5

  17. Another Example char ch; ch = ‘A’; char* q; q = &ch; *q = ‘Z’; char* p; p = q; // the rhs has value 4000 // now p and q both point to ch 4000 A ch 5000 6000 4000 4000 q p Z

  18. Another Example char ch = ‘A’; char* q = &ch; char ch2 = ‘Z’; char* p = &ch2; *p = *q; // now what p points to has the // same value as what q points to 4000 6000 A Z ch ch2 5000 7000 4000 6000 q p A

  19. The NULL Pointer There is a pointer constant 0 called the “null pointer” denoted by NULL in header file cstddef. Indicates that pointer is not pointing to storage of a valid object. But NULL is not memory address 0. (value of 0, but not memory address 0) NOTE: It is an error to dereference a pointer whose value is NULL. Such an error may cause your program to crash, or behave erratically. It is the programmer’s job to check for this. while (ptr != NULL) { // while (ptr) . . . // ok to use *ptr here }

  20. Member Indirection • Consider TimeType t(1,15,0); TimeType *tPtr = &t; • To select a member of t through indirection using tPtr operator precedence requires we do the following (*tPtr).Increment(); • This syntax is clumsy, so C++ provides the indirect member selector operator -> tPtr->Increment(); Invokes member Insert of the object to which tPtr points (t) Invokes member Insert of the object to which tPtr points (t)

  21. Constants and Pointers • A constant pointer is a pointer object where we cannot change the location to which the pointer points char c = 'c'; const char d = 'd'; char * const ptr1 = &c; ptr1 = &d; // illegal c d 40005000 4000 ptr1 // value in ptr1 is constant

  22. Constants and Pointers • A pointer to a constant value is a pointer object where the value at the location to which the pointer points is consider constant const char d = 'd'; const char *ptr2 = &d; *ptr2 = 'e';// illegal: cannot change d through // indirection with ptr2 d 4000 4000 ptr2 // value ptr2 points to is // constant

  23. Pointers and Arrays arrays also store addresses 3000 int *p; a int a[10]; 3000 p = a; // legal (a == &a[ 0 ]) a = p; // illegal (why?) p

  24. Typedefs with Pointers typedef int* IntPtr; IntPtr p; 2 advantages: • int* p1, p2;//creates only 1 pointer p1 versus IntPtr p1, p2;// creates 2 pointers • pointer reference arguments void temp_func (IntPtr &ptr);

  25. typedef int* IntPtr; void main( ) { IntPtr p; int a[10]; int index; for (index = 0; index < 10; index++) a[index] = index; p = a; for (index = 0; index < 10; index++) cout << p[index] << " "; cout << endl; for (index = 0; index < 10; index++) p[index] = p[index] + 1; for (index = 0; index < 10; index++) cout << a[index] << " "; cout << endl; }

  26. Pointer Operation Precedence Precedence Higher->Select member of class pointed to Unary: ++ -- ! * new delete Increment, Decrement, NOT, Dereference, Allocate, Deallocate + - Add Subtract < <= > >= Relational operators == != Tests for equality, inequality Lower = Assignment

  27. Memory Allocation • It is also possible, during execution of the program, to allocate new memory to the program to store variable values. • This is done by using the new and delete operators (not functions)

  28. 3 Kinds of Program Data • STATIC DATA: memory allocation exists throughout execution of program static long currentSeed; • AUTOMATIC DATA: automatically created at function entry, resides in activation frame of the function, and is destroyed when returning from function • DYNAMIC DATA: explicitly allocated and deallocated during program execution by C++ instructions written by programmer using operators new and delete

  29. Allocation of Memory static and automatic data dynamic data DYNAMIC ALLOCATION Dynamic allocation is the allocation of memory space at run time by using operator new. STATIC ALLOCATION Static allocation is the allocation of memory space at compile time.

  30. Operator new Syntax new DataType If memory is available, in an area called the heap (or free store) new allocates the requested object or array, and returns a pointerto (address of ) the memory allocated. Otherwise, program terminates with error message. The dynamically allocated object exists until the delete operator destroys it.

  31. Dynamically Allocated Data char* ptr; ptr = new char; *ptr = ‘B’; cout << *ptr; 2000 ptr

  32. Dynamically Allocated Data char* ptr; ptr = new char; *ptr = ‘B’; cout << *ptr; NOTE: Dynamic data has no variable name 2000 ptr 3000 3000

  33. Dynamically Allocated Data char* ptr; ptr = new char; *ptr = ‘B’; cout << *ptr; NOTE: Dynamic data has no variable name 2000 ptr 3000‘B’ 3000

  34. Using Operator delete Operator delete returns to the free store memory which was previously allocated at run-time by operator new. The object or array currently pointed to by the pointer is deallocated, and the pointer is considered unassigned. 34

  35. Operator delete Syntax delete Pointer If the value of the pointer is 0 there is no effect. Otherwise, the object or array currently pointed to by Pointer is deallocated, and the value of Pointer is undefined. The memory is returned to the free store. Square brackets are used with delete to deallocate a dynamically allocated array.

  36. Dynamically Allocated Data char* ptr; ptr = new char; *ptr = ‘B’; cout << *ptr; Where we were... 2000 ptr 3000‘B’ 3000

  37. Dynamically De-Allocated Data char* ptr; ptr = new char; *ptr = ‘B’; cout << *ptr; delete ptr; ptr = NULL; Memory deallocated, but memory address untouched 2000 ptr NOTE: delete deallocates the memory pointed to by ptr 3000

  38. Dynamically De-Allocated Data char* ptr; ptr = new char; *ptr = ‘B’; cout << *ptr; delete ptr; ptr = NULL; Set memory pointer to NULL. 2000 ptr NULL

  39. Check Yourself void main( ) { int *p1, *p2; p1 = new int; *p1 = 42; p2 = p1; cout << "*p1 == " << *p1 << endl; cout << "*p2 == " << *p2 << endl; *p2 = 53; cout << "*p1 == " << *p1 << endl; cout << "*p2 == " << *p2 << endl; p1 = new int; *p1 = 88; cout << "*p1 == " << *p1 << endl; cout << "*p2 == " << *p2 << endl; *p2 = *p1; cout << "*p1 == " << *p1 << endl; cout << "*p2 == " << *p2 << endl; }

  40. What happens here? int* ptr = new int; *ptr = 3; ptr = new int;// changes value of ptr *ptr = 4; 3 ptr 3 ptr 4

  41. Inaccessible Object An inaccessible object is an unnamed object that was created by operator new and which a programmer has left without a pointer to it. int* ptr = new int; *ptr = 8; int* ptr2 = new int; *ptr2 = -5; 8 ptr -5 ptr2

  42. Making an Object Inaccessible 8 ptr -5 ptr2 int* ptr = new int; *ptr = 8; int* ptr2 = new int; *ptr2 = -5; ptr = ptr2; // here the 8 becomes inaccessible 8 ptr -5 ptr2

  43. Memory Leak A memory leak is the loss of available memory space that occurs when dynamic data is allocated but never deallocated.

  44. A Dangling Pointer is a pointer that points to dynamic memory that has been deallocated int* ptr = new int; *ptr = 8; int* ptr2 = new int; *ptr2 = -5; ptr = ptr2; 8 ptr -5 ptr2 FOR EXAMPLE,

  45. Leaving a Dangling Pointer int* ptr = new int; *ptr = 8; int* ptr2 = new int; *ptr2 = -5; ptr = ptr2; delete ptr2; // ptr is left dangling ptr2 = NULL; 8 ptr -5 ptr2 8 ptr NULL ptr2

  46. Pointers as Function Arguments typedef int* IntPointer; void sneaky(IntPointer temp, IntPointer new_one); void main( ) { IntPointer p, q; p = new int; *p = 77; cout << "Before call to function *p == " << *p << endl; sneaky (p, q); cout << "After call to function *p == " << *p << endl; *q = 52; } void sneaky (IntPointer temp, IntPointer new_one) { *temp = 99; cout << "Inside function call *temp == " << *temp << endl; new_one = new int(12); cout << "Inside function call *new_one == " << *new_one << endl; }

  47. Memory Diagram main p 77 sneaky( p, q ) q sneaky void sneaky (IntPointer temp, IntPointer newOne) { *temp = 99; cout << "Inside function *temp == " << *temp << endl; new_one = new int(12); cout << "Inside function *new_one == " << *new_one << endl; } temp new_one

  48. Ptrs as Reference Arguments typedef int* IntPointer; void sneaky(IntPointer &temp, IntPointer &new_one); void main( ) { IntPointer p, q; p = new int; *p = 77; cout << "Before call to function *p == " << *p << endl; sneaky (p, q); cout << "After call to function *p == " << *p << endl; *q = 52; } void sneaky (IntPointer &temp, IntPointer &new_one) { *temp = 99; cout << "Inside function call *temp == " << *temp << endl; new_one = new int(12); cout << "Inside function call *new_one == " << *new_one << endl; }

  49. Memory Diagram main p 77 sneaky( p, q ) q sneaky void sneaky (IntPointer &temp, IntPointer &newOne) { *temp = 99; cout << "Inside function *temp == " << *temp << endl; new_one = new int(12); cout << "Inside function *new_one == " << *new_one << endl; } temp new_one

  50. Why do we learn pointers? • Remember iterators for the vector class? • They’re really pointers! • Iterators for many container classes are implemented as pointers.