Potential memory leak in SftpSession.cs

Sep 27, 2012 at 8:18 AM


I recently discovered potential memory leak in RenciSsh.Net library. The problem occurs if you use SFTP client to upload asynchronously or synchronously a large file (3 GB approx.) to the remote machine. I was able to partially debug this issue (async pattern is powerful but it is also very hard to debug especially for me not knowing the architecture of this library) and track following method which might cause the problem:

        private void HandleResponse(SftpResponse response)
            SftpRequest request = null;
            lock (this._requests)
                this._requests.TryGetValue(response.ResponseId, out request);
                if (request != null)

            if (request == null)
                throw new InvalidOperationException("Invalid response.");


It looks, like _requests.Remove call does not always remove elements from the dictionary causing it to filling memory with System.Byte[] objects.

To help you further with the investigation, I attached screenshots from the memory profiler for this library:





Apologies for a high images resolution.

Dec 20, 2012 at 6:50 PM



Well, the logic here is this.

Based on protocol SFTP can send multiple request and receive back multiple request but it might be not in the same order

so basically I need to track all the requests I m sending and handle them accordingly.

Cause in theory you could simultaneously upload file, get directory and download file, all using the same channel.

I guess what you can do is see if you ever receive a response that does not have a request in the queue.

In theory it should never happen but may be its a case.