Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
bgColor#FFcccc
class ShowHeapError {
    private Vector<String> names = new Vector<String>();
    private final InputStreamReader input;
    private final BufferedReader reader;

    public ShowHeapError(String filename) throws IOException {
        this.input = new FileReader(filename);
        this.reader = new BufferedReader(input);
    }

    public void addNames() throws IOException {
        String newName;
        while (((newName = reader.readLine()) != null) &&
               (newName.equalsIgnoreCase("quit") == false)) {
            names.addElement(newName);
            System.out.println("adding " + newName);
        }
        input.close();
    }

    public static void main(String[] args) throws IOException {
    if    if (args.length != 1) {
            System.out.println("Arguments: [filename]");
            return;
        }
        ShowHeapError demo = new ShowHeapError(args[0]);
        demo.addNames();
    }
}

Wiki Markup
The code places no upper bounds on the memory space required to execute the program. Consequently, the program can easily exhaust the available heap space in two ways. First, an attacker can supply arbitrarily many lines in the file, causing the vector to grow until memory is exhausted.  Second, an attacker can simply supply an arbitrarily long line, causing the {{readLine()}} method to exhaust memory. According to the Java API \[[API 2006|AA. Bibliography#API 06]\], {{BufferedReader.readLine()}} method documentation

...

Code Block
bgColor#ccccff
class ShowHeapError {
    // ... other methods

    static public String readLimitedLine(Reader reader, int limit) throws IOException {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < limit; i++) {
            int c = reader.read();
            if (c == -1) {
                return nullreturn null;
            }
            if (((char) c == '\n') || ((char) c == '\r')) {
                break;
            }
            sb.append((char) c);
        }
        return sb.toString();
    }

    static public final int lineLengthLimit = 1024;
    static public final int lineCountLimit = 1000000;

    public void addNames() throws IOException {
        String newName;
        for (int i = 0; i < lineCountLimit; i++) {
            newName = readLimitedLine( reader, lineLengthLimit);
            if (newName == null) {
         null) {
        break;
            }
            if (newName.equalsIgnoreCase("quit")) {
                break;
            }

            names.addElement(newName);
            System.out.println("adding " + newName);
        }
        input.close();
    }

}

The readLimitedLine() method defined above takes a numeric limit, indicating the total number of characters that may exist on one line. If a line contains more characters, the line is truncated, and they are returned on the next invocation. This prevents an attacker from exhausting memory by supplying input with no line breaks.

...

Code Block
bgColor#ccccff
class ShowHeapError {
    // ...other methods
    static public final int fileSizeLimit = 1000000;

    public ShowHeapError(String filename) throws IOException {
        if (Files.size( Paths.get( filename)) > fileSizeLimit) {
            throw new IOException("File too large");
        }
        this.input = new FileReader(filename);
        this.reader = new BufferedReader(input);
    }
}

Noncompliant Code Example

...

Code Block
bgColor#FFcccc
/** Assuming the heap size as 512 MB (calculated as 1/4th of 2 GB RAM = 512 MB)
 *  Considering long values being entered (64 bits each, the max number of elements
 *  would be 512 MB/64bits = 67108864)
 */
public class ShowHeapError {
   Vector<Long> names = new Vector<Long>(); // Accepts unknown number of records
   long newID = 0L;
   int count = 67108865;
   int i = 0;
   InputStreamReader input = new InputStreamReader(System.in);
   Scanner reader = new Scanner(input);

   public void addNames() {
     do {
       // Adding unknown number of records to a list
       // The user can enter more IDs than the heap can support and thus 
       // exhaust the heap. Assume that the record ID is a 64 bit long value
      
       System.out.print("Enter recordID (To quit, enter -1): ");
       newID = reader.nextLong();
       
       names.addElement(newID);
       i++;
    } }while (i < count || newID != -1);
     // Close "reader" and "input"
   }

   public static void main(String[] args) {
     ShowHeapError demo = new ShowHeapError();
     demo.addNames();
   }
}

Compliant Solution

A simple compliant solution is to lower the number of names to read.

Code Block
bgColor#ccccff
   // ...
   int count = 10000000;
   // ...

Compliant Solution

Wiki Markup
The {{OutOfMemoryError}} can be avoided by ensuring that the absence of infinite loops, memory leaks, and unnecessary object retention. When memory requirements are known ahead of time, the heap size can be tailored to fit the requirements using the following runtime parameters \[[Java 2006|AA. Bibliography#Java 06]\]:

...