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 results form getStock()
returning null
while main()
forgets to add in a check for such a value. In this noncompliant code example, the check for item != null
is missing from the if
condition in function main()
.
#include <stdio.h> enum { INV_SIZE=20 }; typedef struct { int item[INV_SIZE]; int length; } Inventory; int *getStock(Inventory iv); int main(void) { Inventory iv; size_t i; int *item; iv.length = 0; item = getStock(iv); for (i = 0; i < INV_SIZE; 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> enum { INV_SIZE=20 }; typedef struct { int item[INV_SIZE]; int length; } Inventory; int *getStock(Inventory iv); int main(void) { Inventory iv; size_t i; int *item; iv.length = 0; item = getStock(iv); for (i = 0; i < INV_SIZE; 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 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.
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this guideline on the CERT website.
References
[[Bloch 08]] Item 43: return empty arrays or collections, not nulls