Memory Leaks and Dangling Pointers Lecture 6 Thu

  • Slides: 10
Download presentation
Memory Leaks and Dangling Pointers Lecture 6 Thu, Jan 29, 2004

Memory Leaks and Dangling Pointers Lecture 6 Thu, Jan 29, 2004

Topics l Memory Leaks l Dangling Pointers l The Vector class Set. Size() function

Topics l Memory Leaks l Dangling Pointers l The Vector class Set. Size() function l The Vector class Input() function l Constructors and the new Operator

Memory Leaks l. A memory leak occurs when all pointers to a block of

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

Example: Memory Leaks l Leak. cpp

Example: Memory Leaks l Leak. cpp

Dangling Pointers l l l A dangling pointer is a non-null pointer that points

Dangling Pointers l l l 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.

Example: Dangling Pointers l Dangle. cpp

Example: Dangling Pointers l Dangle. cpp

Example: Vector: : Set. Size() l The Set. Size() function of the Vector class

Example: Vector: : Set. Size() l The Set. Size() 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.

Example: Vector: : Input() l Example: vector. h, vector. cpp, Vector. Test. cpp

Example: Vector: : Input() l Example: vector. h, vector. cpp, Vector. Test. cpp

Example: Vector: : Input() l The Input() function of the Vector class must ¡

Example: Vector: : Input() l 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.

Constructors and the new Operator l The new operator is used in conjunction with

Constructors and the new Operator l The new operator is used in conjunction with the constructors. int* pi = new int(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];