1626
{
BufferReader fil = new BufferReader(new FileReader(fName));
String line;
while ((line = fil.ReadLine()) != null)
{
processLine(line);
}
}
The good code example simply adds an explicit call to the Close() function when the system is
done using the file. Within a simple example such as this the problem is easy to see and fix. In a
real system, the problem may be considerably more obscure.
Example Language: Java (Good)
private void processFile(string fName)
{
BufferReader fil = new BufferReader(new FileReader(fName));
String line;
while ((line = fil.ReadLine()) != null)
{
processLine(line);
}
fil.Close();
}
Example 2:
The following code attempts to open a new connection to a database, process the results returned
by the database, and close the allocated SqlConnection object.
Example Language: C# (Bad)
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(queryString);
cmd.Connection = conn;
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
HarvestResults(rdr);
conn.Connection.Close();
The problem with the above code is that if an exception occurs while executing the SQL or
processing the results, the SqlConnection object is not closed. If this happens often enough, the
database will run out of available cursors and not be able to execute any more SQL queries.
Example 3:
This code attempts to open a connection to a database and catches any exceptions that may
occur.
Example Language: Java (Bad)
try {
Connection con = DriverManager.getConnection(some_connection_string);
}
catch ( Exception e ) {
log( e );
}
If an exception occurs after establishing the database connection and before the same connection
closes, the pool of database connections may become exhausted. If the number of available
connections is exceeded, other users cannot access this resource, effectively denying access to
the application.
CWE Version 4.14
CWE-772: Missing Release of Resource after Effective Lifetime
CWE-772: Missing Release of Resource after Effective Lifetime