Meaningless Drivel is fun!
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Possible Memory Leak Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply locked New topic

Possible Memory Leak

Himanshu Jhamb
Ranch Hand

Joined: Aug 01, 2001
Posts: 134
Consider the following code...
public void f1()
StringBuffer strbuf = null;
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...
[ October 15, 2002: Message edited by: Himanshu Jhamb ]

Himanshu Jhamb<br />SCJP2 v1.2 (April 2002)<br />SCJP2 v1.4 (May 2002)
Vin Kris
Ranch Hand

Joined: Jun 17, 2002
Posts: 154
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 ]
Michael Ernest
High Plains Drifter

Joined: Oct 25, 2000
Posts: 7292

Please view this topic in JiG (Beginner) if interested. --> here
[ October 15, 2002: Message edited by: Jessica Sant ]

Make visible what, without you, might perhaps never have been seen.
- Robert Bresson
I agree. Here's the link:
subject: Possible Memory Leak
It's not a secret anymore!