问题描述
user:surendra nath
在此上的回答指出,OP发布的代码存在内存泄漏,而在大多数情况下,我遇到的情况是,当我们无法释放动态分配的内存区域但在OPs代码中看不到任何动态分配时,就会发生泄漏.他在此处引用了这个Wiki定义.
An answer by user:surendra nath
on this post stated that the code posted by OP has a memory leak, whereas, most of the time I've come across that a leak occurs when we fail to free a dynamically allocated memory region but I couldn't see any dynamic allocation in OPs code.He quoted this wiki definition, here.
从user:artificial idiot
到 post 的内存泄漏的另一个定义是:
And another definition of Memory Leak from user:artificial idiot
to post was:
所以,我的问题:
- 考虑到人工白痴"或维基百科给出的内存泄漏的定义,OP代码上的"surendra nath"所陈述的观点是否可以说是内存泄漏?如果是这样,那为什么呢?
- C中的内存泄漏是否总是指释放先前动态分配的内存失败?
P.S. -我不知道Wiki& 人工白痴"具有相同的含义,因为Wiki定义有时过于宽泛以至于无法理解.
P.S. - I don't know if the definitions from wiki & "artificial idiot" have the same meaning, since wiki definitions are sometimes too broad to understand.
推荐答案
人工白痴在有时可能会引起关注.假设您有一个执行以下操作的程序:
The issue that artificial idiot raises in The Best Memory Leak Definition can sometimes be a concern. Suppose you have a program that does something like this:
- 构造一百万个动态分配对象的数组.
- 对该数组进行处理.
- 构造另一个由100万个动态分配的对象组成的数组(在第一个数组中未引用任何对象).
- 对该数组进行处理.
- 释放第二个数组.
- 释放第一个数组.
在步骤3-5中,即使不需要任何数据,第一个阵列仍在使用内存.结果,整个程序使用的总内存是实际需要的两倍.如果不再需要它,它应该在第2步之后释放第一个数组-然后可以将其内存重新用于第二个数组.
During steps 3-5, the first array is still using memory, even though none of its data is needed. As a result, the program as a whole uses twice as much total memory as it really needs. It should free the first array after step 2 if it no longer needs it -- then its memory could be reused for the second array.
这是一种即使在垃圾收集语言中也可能发生的内存泄漏-如果保留对第一个数组的引用的变量没有被重新分配或超出范围,它将阻止所有数据被存储. GC'ed.
This is the kind of memory leak that can occur even in garbage-collected languages -- if the variable holding the reference to the first array doesn't get reassigned or go out of scope, it will keep all that data from being GC'ed.
一个足够聪明的优化器理论上可以自动解决此问题.如果它可以分析控制和数据流,并确定在第2步之后从未使用过第一个数组,则可以将第6步重新排序到该位置.但是在很多情况下,编译器可能很难确定这一点.
A sufficiently clever optimizer could theoretically address this automatically. If it can analyze the control and data flow, and determine that the first array is never used after step 2, it could reorder step 6 to that place. But in many cases it may be difficult for the compiler to determine this.
编写模块化代码通常可以避免类似的问题.如果创建用于处理每个数组的单独函数,则这些函数应分配它们,使用它们并释放它们.
Writing modular code will often avoid problems like this. If you create separate functions for processing each of the arrays, the functions should allocate them, use them, and free them.
这篇关于这是C中的内存泄漏吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!