Allocation within infinite loop

JD.INF.ALLOC occurs when large sections of memory are consumed within an infinite loop and there is no verification of available memory.

Vulnerability and risk

The software does not properly control memory allocation. If an attacker can trigger the uncontrolled allocation of memory, that can eventually lead to the exhaustion of available resources, also known as a Denial of Service attack. Denial of Service attacks can slow down the application as well as its host operating system, prevent valid users from accessing the software, and can potentially have an impact on the surrounding environment.

Mitigation and prevention

Do an available memory check, and do not use infinite loops. For example, use the Runtime.getRuntime().freeMemory() method to check the available free memory.

Vulnerable code example

1   while(true)
2   {
3     byte[] b = new byte[NUMBER];
4     list.add(b);
5   }

In the above example, infinite allocation can lead to an OutOfMemoryError exception. Klocwork reports a JD.INF.ALLOC defect at line 3, indicating, "Memory allocation within infinite loop can lead to OutOfMemoryError".

Fixed code example

1   while(true)
2   {
3     if (Runtime.getRuntime().freeMemory() > NUMBER) {
4       byte[] b = new byte[NUMBER];
5       list.add(b);
6     }
7   }

Adding a check for available free memory by using the Runtime.getRuntime().freeMemory() method fixes the problem.