9.12 Memory Leaks

未经允许,不可转载。禁止商用。欢迎学术交流讨论和指正。

Commercial use are prohibited, only for academic-purposed discussion and learning.

 

Memory leak - A program that allocates memory but then loses the ability to access that memory

Why: failure to properly destroy/free dynamically allocated memory.

Analogy: a water pipe have water leaking out and becoming unusable;

             - a  program's available memory has portions leaking out and becoming unusable.

Consequence: a program occupies more and more memory as program runs

                           occupying memories  - 

                                1. slow program runtime

                                2. program failure if the memory becomes completely full and unable to allocate additional memory



Demo 9.12.1 Memory leak can use up all available memory

9.12 Memory Leaks_第1张图片
Memory leak can use up all available memory


1st iteration

a) Memory is allocated for newVal each loop iteration, 

b) the loop does NOT deallocate memory once done using newVal,

c) result in a memory leak

85 _______

86 _______ memory for newVal

87 _______

88 _______

89 _______

90 _______

91 _______

92 _______

2nd, 3rd, 4th, 5th, .... iterations

a) each loop iteration allocates more memory

b) eventually using up all available memory

c) causing the program to fail

85 _______

86 _______ memory for newVal

87 _______ memory for newVal

88 _______ memory for newVal

89 _______ memory for newVal

90 _______ memory for newVal

91 _______ memory for newVal

92 _______ memory for newVal



Common error: failing to free allocated memory when done using that memory -- > a memory leak

Who: programs that are commonly left running for long periods.

Ex. web browsers " memory leak"

Solution:

Java - garbage collection 

1) a program's executable includes automatic behavior that at various intervals finds all unreachable allocated memory   locations

        - by comparing all reachable memory with all previously-allocated memory

2) automatically freeing such unreachable memory

C/C++ - unstandardized garbage collection 

garbage collection 

pro: reduce the impact of memory leaks

con: runtime overhead

Debate: new programmers should learn to explicitly free memory vs. letting garbage collection do the work



Exercises 9.12.2: Memory leaks

Question 1: Memory locations that have been dynamically allocated but can no longer be used by a program

Answer 1: Unusable memory

Question 2: Occurs when a program allocates memory but loses the ability to access that memory.

Answer 2: Memory leak

Question 3: Automatic process of finding unreachable allocated memory locations freeing that unreachable memory.

Answer 3: Garbage collection

你可能感兴趣的:(9.12 Memory Leaks)