重复使用全局变量数组int []会导致系统资源分配泄漏吗? [英] Repeat use the global variable array int [] will cause the system resource assignment leaks?

查看:80
本文介绍了重复使用全局变量数组int []会导致系统资源分配泄漏吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个全局变量int [] t,以下函数,现在多次调用该函数,每次长度不同,这个动作会导致内存泄漏吗?



I have a global variable int [] t, and the following function, now calls the function multiple times, the length different every time,this action will cause a memory leak it?

static int[] t; // global variable

void testIt(int length)
{
    int[] temp = new int[length];
    for(int i=0;i<length;i++)
    {
        temp[i]=i;
    }
    t = temp;
}

推荐答案

首先,请忽略解决方案1.不幸的是,这个成员对此没有任何线索和一些相关的主题。

请看我对这个问题的评论:.NET中没有全局变量这样的东西(这太好了!)。



别担心,它原则上不会导致内存泄漏。受管系统中的内存使用由垃圾收集控制。当某个对象变得无法访问时,它会发挥作用。这里有更详细的解释:

http://en.wikipedia.org/ wiki / Garbage_collection_%28computer_science%29 [ ^ ]。



也就是说,这并不意味着在托管系统中内存泄漏是不可能的。他们是可能的!但是,大多数情况下都会阻止意外内存泄漏。人们真正创造的内存泄漏更多是错误的一般代码设计。我在过去的答案中解释过:

WPF DataBinding中的内存泄漏 [ ^ ],

MDI表单中的内存管理 [ ^ ],

摆脱的最佳途径导致内存不足的公共静态列表 [ ^ ],

推迟循环中的变量会导致内存泄漏吗? [ ^ ],

Garbage collectotion负责所有内存管理 [ ^ ]。



-SA
First of all, please disregard Solution 1. Unfortunately, this member has no clue on this and some related topics.
And please see my comment to the question: there is no such thing as "global variable" in .NET (and this is so-o good!).

Don't worry, it cannot cause a memory leak in principle. Memory use in managed systems is controlled by the Garbage Collection. It comes into play when some object becomes unreachable. This is explained in more detail here:
http://en.wikipedia.org/wiki/Garbage_collection_%28computer_science%29[^].

That said, it does not mean that memory leaks are impossible in managed systems. They are possible! However, "accidental" memory leak are mostly prevented. The memory leaks people really create are more of the wrong general design of the code. I explained it in my past answers:
Memory leak in WPF DataBinding[^],
Memory management in MDI forms[^],
Best way to get rid of a public static List Causing an Out of Memory[^],
deferring varirable inside the loop can cuase memory leak?[^],
Garbage collectotion takes care of all the memory management[^].

—SA


是的,它会造成内存泄漏。



调用第一次调用函数时比在堆中分配的内存并且返回到temp分配给t,

现在当第二次再次调用此函数时,将在堆中创建新内存并返回地址new与上一个不同并分配给t。



所以保存在静态变量t中的第一个堆内存地址丢失,不会从堆中删除。因此内存泄漏同意。
Yes it cause memory leak.

when first time function is called than memory allocated at heap and addressed returned to temp which is assigned to t,
now when second time this function is called again new memory is created at heap and address is returned by new which is different from previous one and assigned to t.

so first heap memory address which is save in static variable t is lost which is not deleted from heap. Hence memory leak concurred.


这篇关于重复使用全局变量数组int []会导致系统资源分配泄漏吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆