-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathImproperValidationOfArrayConstruction.qhelp
More file actions
38 lines (34 loc) · 1.86 KB
/
ImproperValidationOfArrayConstruction.qhelp
File metadata and controls
38 lines (34 loc) · 1.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<!DOCTYPE qhelp PUBLIC
"-//Semmle//qhelp//EN"
"qhelp.dtd">
<qhelp>
<overview>
<p>Using unvalidated input when specifying the size of a newly created array can result in the
creation of an array with size zero. If this array is subsequently accessed without further checks,
an <code>ArrayIndexOutOfBoundsException</code> may be thrown, because there is no guarantee that
the array is not empty.</p>
<p>This problem occurs when user input is used as the size during array initialization, either directly
or following one or more calculations. If the user input is unvalidated, it may cause the size of
the array to be zero.</p>
</overview>
<recommendation>
<p>
The size used in the array initialization should be verified to be greater than zero before being
used. Alternatively, the array access may be protected by a conditional check that ensures it is
only accessed if the index is less than the array size.</p>
</recommendation>
<example>
<p>The following program constructs an array with the size specified by some user input:</p>
<sample src="ImproperValidationOfArrayConstruction.java" />
<p>The first array construction is protected by a condition that checks if the user input is zero
or more. However, if the user provides <code>0</code> as the <code>numberOfItems</code> parameter,
then an empty array is created, and any array access would fail with an
<code>ArrayIndexOutOfBoundsException</code>.</p>
<p>The second array construction is protected by a condition that checks if the user input is
greater than zero. The array will therefore never be empty, and the following array
access will not throw an <code>ArrayIndexOutOfBoundsException</code>.</p>
</example>
<references>
<li>Java API Specification: <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/ArrayIndexOutOfBoundsException.html">ArrayIndexOutOfBoundsException</a>.</li>
</references>
</qhelp>