1 / 28

2. Pointer

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

ilya
Download Presentation

2. Pointer

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 2. Pointer Yan Shi CS/SE2630 Lecture Notes

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

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

  4. 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

  5. For a normal variable • intnum; Memory Address identifier . . . ? num 0010 . . . . . .

  6. For a normal variable • intnum; • num = 50; Memory Address identifier . . . 50 num 0010 . . . . . .

  7. Pointer • intnum; • num = 50; • int *p; Memory Address identifier . . . 50 num 0010 ? 0012 p A pointer variable contains the memory address of another variable. . . . . . .

  8. Pointer • intnum; • num = 50; • int *p; • p = # Memory Address identifier . . . 50 num 0010 0010 0012 p & is the address-of operator. . . . . . .

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

  10. Pointer • intnum; • num = 50; • int *p; • p = &num; • cout << *p; • *p = 100; Memory Address identifier . . . //direct addressing 100 num 0010 0010 0012 p . . . //indirect addressing change the value at the address p points to to 100 . . .

  11. Another Example 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 4000 A Z ch 5000 6000 4000 4000 q p

  12. 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 • <cstddef> 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.

  13. 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

  14. Dynamic Memory Allocation • int *p = new int; Memory Address identifier . . . p 0010 . . . . . .

  15. Dynamic Memory Allocation • int *p = new int; Memory Address identifier . . . p 0010 . . . unnamed dynamically allocated integer variable (from heap) ? 0080 . . .

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

  17. 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.

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

  19. 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.

  20. 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();

  21. 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 complicated.

  22. 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.

  23. Deallocate Memory: delete • deleteoperator 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.

  24. 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, _CrtDumpMemoryLeaksdisplays memory leak information in the Output window. #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h>

  25. 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!

  26. 8 ptr -5 ptr2 Dangling Pointer Example int* ptr = new int; *ptr = 8; int* ptr2 = new int; *ptr2 = -5; ptr = ptr2;

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

  28. 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; }

More Related