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

Copy
   using System.IO;
    
   namespace Example
   {
       class Program
       {
           static void Main(string[] args)
           {
               BinaryWriter bw = new BinaryWriter(new FileStream("aaa.txt", FileMode.Open)); // Or, any other IDisposable
              bw.Dispose();
   
              bw.Write("bbb"); //@ CS.UFR. We are accessing the resource after it has been disposed of.
          }
   
      }
  }

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

Copy
   using System.IO;
    
   namespace Example
   {
       class Program
       {
           static void Main(string[] args)
           {
               BinaryWriter bw = new BinaryWriter(new FileStream("aaa.txt", FileMode.Open)); // Or, any other IDisposable
              bw.Write("bbb"); //@no CS.UFR.
              bw.Dispose();
          }
   
      }
  }

External guidance

Security training

Application security training materials provided by Secure Code Warrior.