Sometimes null
is returned intentionally Functions may intentionally return null
to account for zero available instances. This practice can lead to vulnerabilities when the client code does not correctly handle the null
return case.
Noncompliant Code Example
The erroneous behavior is caused due to getStock
results form getStock()
returning null
while main()
forgets to add in a check for such a value. This In this noncompliant code example shows how , the check for item != null
condition is missing from the if
condition in function main()
.
Code Block | ||
---|---|---|
| ||
#include <stdio.h> typedef struct { int item[20]; int length; } Inventory; int * getStock(Inventory iv); int main (int argc, char* argv[]) void) { Inventory iv; intsize_t i; int * item; iv.length = 0; item = getStock(iv); for (i = 0; i < 20; i++) { if (item[i] == 1) { printf("Almost out of stock of item: %d", i); } } return 0; } int * getStock(Inventory iv) { if (iv.length == 0) { return NULL; } else { return iv.item; } } |
...
Code Block | ||
---|---|---|
| ||
#include <stdio.h> typedef struct { int item[20]; int length; } Inventory; int * getStock(Inventory iv); int main (int argc, char* argv[]) (void) { Inventory iv; intsize_t i; int * item; iv.length = 0; item = getStock(iv); for (i = 0; i < 20; i++) { if (item[i] == 1) { printf("Almost out of stock of item: %d", i); } } return 0; } int * getStock(Inventory iv) { return iv.item; } |
Risk Assessment
...
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
MSC19-C | low | unlikely | high | P1 | L3 |
Other Languages
This rule guideline appears in the Java Secure Coding Standard as MET03-J. For methods that return an array or collection prefer returning an empty array or collection over a null value.
...
Search for vulnerabilities resulting from the violation of this rule guideline on the CERT website.
References
...