1 / 10

Memory Leaks and Dangling Pointers

Memory Leaks and Dangling Pointers. Lecture 6 Thu, Jan 29, 2004. Topics. Memory Leaks Dangling Pointers The Vector class SetSize() function The Vector class Input() function Constructors and the new Operator. Memory Leaks.

presta
Download Presentation

Memory Leaks and Dangling Pointers

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. Memory Leaks and Dangling Pointers Lecture 6 Thu, Jan 29, 2004

  2. Topics • Memory Leaks • Dangling Pointers • The Vector class SetSize() function • The Vector class Input() function • Constructors and the new Operator

  3. Memory Leaks • A memory leak occurs when all pointers to a block of allocated memory have been lost. • Leaked memory cannot be accessed or reallocated. • Excessive memory leaks may cause the program to run out of usable memory and crash. • Memory leaks should always be avoided.

  4. Example: Memory Leaks • Leak.cpp

  5. Dangling Pointers • A dangling pointer is a non-null pointer that points to unallocated memory. • Dereferencing a dangling pointer may cause the program to crash. • It impossible to test a pointer to see if it is dangling. • Always set pointers to NULL if they do not point to allocated memory. • Dangling pointers must always be avoided.

  6. Example: Dangling Pointers • Dangle.cpp

  7. Example: Vector::SetSize() • The SetSize() function of the Vector class must • Allocate new memory of the specified size. • Copy the old values into the new memory. • Deallocate the memory that the Vector is currently using. • Redirect the Vector to the new memory.

  8. Example: Vector::Input() • Example: vector.h, vector.cpp,VectorTest.cpp

  9. Example: Vector::Input() • The Input() function of the Vector class must • Deallocate the memory that the Vector is currently using (if any). • Allocate new memory for the values to be input. • Continue to increase the allocated memory as more values are read.

  10. Constructors and the new Operator • The new operator is used in conjunction with the constructors. int* pi = newint(123); string* ps = new string("Hello"); Rational* pr = new Rational(2, 3); Date* pd = new Date("Jan", 23, 2002); Point* ppt = new Point; int* pai = new int[123]; Point* papt = new Point[10];

More Related