Dynamic Memory Management CSCE 121 Memory Leaks Lose

  • Slides: 5
Download presentation
Dynamic Memory Management CSCE 121

Dynamic Memory Management CSCE 121

Memory Leaks • Lose access to memory allocated on the heap. • Easy to

Memory Leaks • Lose access to memory allocated on the heap. • Easy to lose when dealing with pointers • We want to avoid!!! • Sometimes conflated with poor memory management.

Managing Memory • Programmer gets memory from the heap • Programmer must free it

Managing Memory • Programmer gets memory from the heap • Programmer must free it when done • Commonly referred to as garbage collection. • Good exam question • What are specific scenarios that can result in a memory leak? • Think about the definition of a memory leak as we continue to discuss dynamic memory management.

Strategies to Manage Dynamic Memory (i. e. do garbage collection) l a c i

Strategies to Manage Dynamic Memory (i. e. do garbage collection) l a c i t c • Avoid using dynamic memory. Impra s a d a o r b • Balance allocation with deallocation. Too. y g e t a • news with deletes r t s a e s u , t n • Automatic Garbage Collection e. i e c i g f a f u g Ine n a • While these do exist for C++, l t n e r tend to be inefficient and slow things down. a diffe • RAII – Resource Allocation is Initialization • When possible • allocate in the constructor • deallocate in the destructor ! d e r r e f e r P

Dynamic Classes • Classes that use dynamic memory, must implement certain functions to effectively

Dynamic Classes • Classes that use dynamic memory, must implement certain functions to effectively manage memory on the heap. • Rule of Three If you implement one of the following, you must implement the other two! • Destructor Things will b reak if you d • Copy Assignment o not imple ment these • Copy Constructor ! • Rule of Five (We won’t cover these) • Move Assignment Things will w ork, but not efficiently! • Move Constructor • We’ll see more on these later.