JD.INF.ALLOC
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
while(true)
{
byte[] b = new byte[NUMBER];
list.add(b);
}
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
while(true)
{
if (Runtime.getRuntime().freeMemory() > NUMBER) {
byte[] b = new byte[NUMBER];
list.add(b);
}
}
Adding a check for available free memory by using the Runtime.getRuntime().freeMemory() method fixes the problem.