Robert Klemme
4/1/2007 4:13:00 PM
On 31.03.2007 10:24, Brian Candler wrote:
> On Fri, Mar 30, 2007 at 04:10:04PM +0900, Robert Klemme wrote:
>> On 28.03.2007 23:41, Pratik wrote:
>>> I've already called GC.start and yet some objects are not being freed.
>>> However, I'm still uncertain about memory leaks in ruby code and
>>> looking for an example of any such case.
>> A memory leak comes into existence when some piece of code holds longer
>> onto an instance than necessary / intended. Look at this:
>>
>> class Foo
>> @instances = []
>>
>> def self.register(obj)
>> @instances << obj
>> end
>>
>> def initialize
>> Foo.register(self)
>> end
>> end
>>
>> Instances register with their class but never deregister - so they can
>> never be collected and use up memory. My guess would be that you'll
>> have a hard time writing a program that is able to track these without
>> actually running the code.
>
> IMO, that's not a memory leak, that's correct behaviour.
From the interpreter's point of view.
> You created some
> objects and purposely held on to references to them. At any point later in
> the code someone might do Foo.class_eval { @instances.[n] }
While this might actually happen, the issue I tried to convey is that no
instances of class Foo will never be collected because @instances holds
on to all of them. If this is intended then this is of course not a
leak but as my explanation should have made clear this was not intended
in the example. I probably should have been clearer about this.
> My definition of a memory leak would be when memory has been allocated but
> there are *no* remaining references to it available anywhere, meaning that
> it has been effectively lost and can never be freed.
This cannot happen in Ruby and Java. In these languages the term
"memory leak" is actually used for memory that cannot be freed because
something holds on to it longer than intended.
> This shouldn't/can't happen in pure Ruby code. But it can certainly happen
> in C extensions, where memory has been malloc()d but the pointer forgotten
> about.
That's another story. But I think the OP was looking for memory leaks
in Ruby code.
Kind regards
robert