Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Possible Memory Leak

 
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Report post to moderator
Hi.
Consider the following code...
public void f1()
{
StringBuffer strbuf = null;
try
{
strbuf = f2(1);
}
catch(Exception e)
{
... // Some code
}
}
public StringBuffer f2(int i)
{
StringBuffer strb = new StringBuffer();
... // Some code that operates on i and puts it into strb
return strb;
}
My Question --> Once the method f2 returns, variable strb goes out of scope. Isn't this a candidate for introducing a memory leak ??? In other words, we are trying to return a variable's reference, which has just gone out of scope?
One possible reason for it not causing a memory leak can be that although the reference is unreachable once f2() returns, it is not null, hence still not a candidate for GC. But, I am not convinced... somehow.
All comments are invited...
thx
[ October 15, 2002: Message edited by: Himanshu Jhamb ]
 
Ranch Hand
Posts: 154
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Report post to moderator
Himanshu, this would have been the case in C/C++ code. It has been a long while since i have even looked at a C code but I recollect the term 'dangling pointer' (a pointer to an auto object) - the object gets destroyed once it goes out of scope but still a pointer is returned -> core dump.
In java, the object is created in the heap. So regardless of scope, it is eligible for GC only if there are no references to the object (excluding weak refs). A reference to this object can be passed around without any concern.
I would definitely not classify this as a memory leak.
[ October 15, 2002: Message edited by: Vin Kris ]
 
High Plains Drifter
Posts: 7289
Netbeans IDE VI Editor
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Report post to moderator
Please view this topic in JiG (Beginner) if interested. --> here
[ October 15, 2002: Message edited by: Jessica Sant ]
 
Don't get me started about those stupid light bulbs.
    Bookmark Topic Watch Topic
  • New Topic