CS.UFR

Using freed resource

Because C# has a garbage collector, it is largely protected from many memory issues. However, objects using unmanaged resources (for example., 'IDisposable' objects) can still be prone to use-after-free bugs. The CS.UFR checker flags the use of disposed resources.

Vulnerability and risk

Accessing an 'IDisposable' object after it has been disposed will result in an exception being thrown, which could cause the program to terminate prematurely if it is not handled.

Vulnerable code example

1   using System.IO;
2    
3   namespace Example
4   {
5       class Program
6       {
7           static void Main(string[] args)
8           {
9               BinaryWriter bw = new BinaryWriter(new FileStream("aaa.txt", FileMode.Open)); // Or, any other IDisposable
10              bw.Dispose();
11   
12              bw.Write("bbb"); //@ CS.UFR. We are accessing the resource after it has been disposed of.
13          }
14   
15      }
16  }
  

In this example, Klocwork reports a CS.UFR defect at line 12, when the code accesses the resource after it has been disposed of.

Fixed code example

1   using System.IO;
2    
3   namespace Example
4   {
5       class Program
6       {
7           static void Main(string[] args)
8           {
9               BinaryWriter bw = new BinaryWriter(new FileStream("aaa.txt", FileMode.Open)); // Or, any other IDisposable
10              bw.Write("bbb"); //@no CS.UFR.
11              bw.Dispose();
12          }
13   
14      }
15  }

External guidance

Security training

Application security training materials provided by Secure Code Warrior.