为什么此代码示例会产生内存泄漏? [英] Why does this code sample produce a memory leak?

查看:107
本文介绍了为什么此代码示例会产生内存泄漏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在大学里,我们得到了下面的代码示例,并且我们被告知,运行此代码时存在内存泄漏。该示例应该证明这是垃圾收集器无法工作的情况。



就我的面向对象的编程而言,唯一能够产生内存泄漏的代码行是

  items = Arrays.copyOf(items,2 * size + 1); 

文档说,元素被复制。这是否意味着引用被复制(并因此创建了堆上的另一个条目)或者该对象本身正在被复制?据我所知,Object和Object []是作为参考类型实现的。因此,为'items'分配一个新的值将允许垃圾收集器发现旧的'item'不再被引用,因此可以被收集。

在我看来,这个codesample不会产生内存泄漏。有人能证明我错了吗? =)

  import java.util.Arrays; 
public class Foo
{
private Object [] items;
private int size = 0;
private static final int ISIZE = 10;

public Foo()
{
items = new Object [ISIZE];
}

public void push(final Object o){
checkSize();
items [size ++] = o;


public Object pop(){
if(size == 0)
throw new /// ...
return items [ - -尺寸];

private void checkSize(){
if(items.length == size){
items = Arrays.copyOf(items,2 * size + 1);




解决方案

提示:泄漏位于 pop 方法中。考虑一下弹出对象的引用会发生什么......


In the university we were given the following code sample and we were being told, that there is a memory leak when running this code. The sample should demonstrate that this is a situation where the garbage collector can't work.

As far as my object oriented programming goes, the only codeline able to create a memory leak would be

items=Arrays.copyOf(items,2 * size+1); 

The documentation says, that the elements are copied. Does that mean the reference is copied (and therefore another entry on the heap is created) or the object itself is being copied? As far as I know, Object and therefore Object[] are implemented as a reference type. So assigning a new value to 'items' would allow the garbage collector to find that the old 'item' is no longer referenced and can therefore be collected.

In my eyes, this the codesample does not produce a memory leak. Could somebody prove me wrong? =)

import java.util.Arrays;
public class Foo  
{  
private Object[] items;  
private int size=0;  
private static final int ISIZE=10;

public Foo()  
{  
  items= new Object[ISIZE];  
}  

public void push(final Object o){  
  checkSize();  
  items[size++]=o;  
}  

public Object pop(){  
  if (size==0)  
    throw new ///...  
  return items[--size];  
}  
private void checkSize(){  
  if (items.length==size){  
    items=Arrays.copyOf(items,2 * size+1);  
  }  
}  
}

解决方案

Hint: the leak is in the pop method. Consider what happens to the references to a popped object ...

这篇关于为什么此代码示例会产生内存泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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