Sometimes null
is returned intentionally to account for zero available instances. This practice can lead to vulnerabilities when the client code does not handle the null
return case.
Noncompliant Code Example
The erroneous behavior is caused due to getStock
returning null
while main
forgets to add in a check for such a value. This noncompliant example shows how the check item != null
condition is missing from the if
condition in function main
.
#include <stdio.h> typedef struct { int item[20]; int length; } Inventory; int* getStock(Inventory iv); int main (int argc, char* argv[]) { Inventory iv; int 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; } }
Compliant Solution
This compliant solution eliminates the null
return and simply returns the item
array as is even if it is zero-length. The main function can effectively handle this situation without exhibiting erroneous behavior.
#include <stdio.h> typedef struct { int item[20]; int length; } Inventory; int* getStock(Inventory iv); int main (int argc, char* argv[]) { Inventory iv; int 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
Returning null
rather than a zero-length array may lead to vulnerabilities when the client code does not handle null
properly.
Rule |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
---|---|---|---|---|---|
MSC19-C |
low |
unlikely |
high |
P1 |
L3 |
Other Languages
This rule 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.
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
References
[[Bloch 08]] Item 43: return empty arrays or collections, not nulls