You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 3 Next »

A Java heap space error occurs if infinite heap space is assumed and the program can crash. This error can be generated due to the following possible reasons:

1. A memory leak

2. An infinite loop

3. The program requires more memory than is present by default in the heap

 Non Compliant Code Example

A heap error will be generated if the heap is continued to be accessed even if there is no memory left in the heap.

import java.io.*;
import java.util.*;

public class ShowHeapError {

    Vector<String> names = new Vector<String>();
    String newName=null;
    InputStreamReader input = new InputStreamReader(System.in);
    BufferedReader reader = new BufferedReader(input);

    public void addNames(){
    	do{
    		//adding unknown number of records to a list
    		System.out.print(" To quit, enter \"quit\"\nEnter record: ");
          	try {
          		newName = reader.readLine();
          		if(!newName.equalsIgnoreCase("quit")){
          			//names are continued to be added without bothering about the size on the heap
          			names.addElement(newName);
          		}
   			} catch (IOException e) {
   			}
            System.out.println(newName);

    	}
        while (!newName.equalsIgnoreCase("quit"));
    }

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

Compliant solution

This exception can be avoided by either making sure that there are no infinite loops or memory leaks. If the programmer knows that the application would require a lot of memory then, he can increase the heap size in Java using the following run time parameters:

java -Xms<initial heap size> -Xmx<maximum heap size>

for example:

java -Xms128m -Xmx512m ShowHeapError

Here we have set the initial  heap size as 128Mb and the maximum heap size as 512Mb.

This setting can be done either in the Java Control Panel or on the command line. This setting cannot be controlled in the application itself.

Risk Assessment

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

FIO37-J

low

probable

medium

P3

L3

 Automated Detection

TODO

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website

 

  • No labels