Subject:
[ruby-ffi] I can't figure out my memory leak
From:
Chuck Remes
Date:
5/7/10 11:26 AM
To:
ruby-ffi@googlegroups.com

http://github.com/chuckremes/ffi-rzmq

I have a tremendous memory leak in my FFI code. I'm pretty sure I know exactly where it is caused but I have no idea how to solve it. This gist shows the code in question.

http://gist.github.com/393627

The first gist block is where I think the memory leak lives. The second gist block is the definition of the leaking Struct and the definitions of the library functions.

Here's the sequence of events for the creation of a message where message is not nil (from the constructor).

1. Allocate the Msg_t Struct.

2. Create a MemoryPointer from the message string to create the Msg_t payload.

3. Hand off the Struct obj to the underlying library and tell the library the size needed to store the data.

4. Hand off the MemoryPointer pointing to the message data to the underlying library. The library should now *own* the memory allocated in step #2 and manage it from here on.


After a call is made to transmit OR receive the message obj, it calls Message#close. This makes a call to the underlying library to close the message and release its memory. This should release the memory that was allocated in #2 above. 

When I run a sample program, memory continually increases (under JRuby) and never gets collected. I know it is related to this code path because I can control the size of the messages being echoed back and forth. The code makes no other sizable memory allocation elsewhere, so I'm pretty confident the culprit is here.

Does anything look amiss? What is the difference between FFI::Pointer and FFI::MemoryPointer? 

Any suggestions on how to debug this?

cr