UF.IN
UF (Use Freed) issues are reported when there is an attempt to use resources after they were released. The UF.IN warning indicates an attempt to use an input stream after it was closed.
Example 1
Copy
public boolean checkMeta(InputStream stream) {
byte[] b = new byte[8];
try {
final long l = stream.available();
if (l < 8) {
return false;
}
stream.read(b);
} catch (IOException e) {
return false;
} finally {
try {
stream.close();
} catch (IOException e) {
// do nothing
}
}
// Cast unsigned character constants prior to comparison
return (b[0] == (byte) 'm' && b[1] == (byte) 'y' &&
b[2] == (byte) 'f' && b[3] == (byte) 'o' &&
b[4] == (byte) 'r' && b[5] == (byte) 'm' &&
b[6] == (byte) 'a' && b[7] == (byte) 't');
}
public void printOut(final URL url, final PrintStream ps) throws IOException {
final InputStream stream = url.openStream();
if (checkMeta(stream)) {
try {
ps.println("content:");
byte[] b = new byte[1024];
int i;
while ((i = stream.read(b)) > 0) {
ps.print(new String(b, 0, i));
}
ps.println();
} catch (IOException e) {
e.printStackTrace();
}
}
}
UF.IN is reported for the snippet on line 50: input stream 'stream' is used after it was closed on line 30.
Example 2
Copy
public boolean checkMeta(InputStream stream) {
byte[] b = new byte[8];
try {
final long l = stream.available();
if (l < 8) {
return false;
}
stream.read(b);
} catch (IOException e) {
return false;
}
// Cast unsigned character constants prior to comparison
return (b[0] == (byte) 'm' && b[1] == (byte) 'y' &&
b[2] == (byte) 'f' && b[3] == (byte) 'o' &&
b[4] == (byte) 'r' && b[5] == (byte) 'm' &&
b[6] == (byte) 'a' && b[7] == (byte) 't');
}
public void printOut(final URL url, final PrintStream ps) throws IOException {
final InputStream stream = url.openStream();
try {
if (checkMeta(stream)) {
try {
ps.println("content:");
byte[] b = new byte[1024];
int i;
while ((i = stream.read(b)) > 0) {
ps.print(new String(b, 0, i));
}
ps.println();
} catch (IOException e) {
e.printStackTrace();
}
}
} finally {
try {
stream.close();
} catch (IOException e) {
// do nothing
}
}
}
The snippet from the previous section is fixed. Method 'checkMeta' no longer closes the stream. Now it is closed by the 'printOut' method, which is the method that opened the stream. In general, it is good coding practice to release resources with the same methods in which they were originally allocated.