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

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 "<your-favorite-browser> 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

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容