CS.RLK

References to an object of type which implements 'IDisposable' interface are lost, but 'Dispose' method is not called.

Vulnerability and risk

Managed classes use the IDisposable interface to allow their consumers to release potentially expensive resources before the garbage collector finalizes the object.

Example 1

1  using System;
2  using System.IO;
3  
4  namespace LeakExample
5  {
6      class Test
7      {
8          public String Run(String name)
9          {
10             StreamReader reader = new StreamReader(name);
11             String result = reader.ReadToEnd();
12             reader.Close();
13             return result;
14         }
15     }
16 }

Klocwork produces an issue report on the example. StreamReader class implements IDisposable interface, the implementation of Close method calls Dispose method. An object of 'StreamReader' type is allocated and its reference is assigned to 'reader' variable. If the call to 'ReadToEnd' throws an exception, control is transferred out of method 'Run', variable 'reader' goes out of scope, object referenced by it becomes lost, but related resources are not disposed.