Improper Resource Allocation
Need
Prevent unnecessary resource consumption due to inefficient algorithms or improper programming practices
Context
- Usage of Elixir (v1.11+) for building scalable and concurrent applications
Description
Non compliant code
defmodule Vulnerable do
def huge_list(n) when is_integer(n) do
Enum.to_list(1..n)
end
end
The huge_list
function creates a list from 1 to n
. If n
is a large number, this function could consume a large amount of memory, possibly leading to an OutOfMemory error or significantly slowing down the system.
Steps
- Consider the nature of the problem you're trying to solve and choose the appropriate data structure.
- If possible, use lazy evaluation to avoid creating large data structures in memory.
- Apply a limit to the input size if it's under external control.
- If the function is intended to create large data structures, consider alternative strategies like writing the data to disk.
Compliant code
defmodule Secure do
def huge_list(n) when is_integer(n) and n <= 10000 do
Enum.to_list(1..n)
end
end
In the secure example, a guard clause has been added to limit n
to 10,000, preventing the creation of extremely large lists. The actual limit should be determined based on the specific requirements and resources of your system.