Prevent unnecessary resource consumption due to inefficient algorithms or improper programming practices
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.
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.