Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Many functions have the option of returning a pointer to an object , or returning NULL if a valid pointer cannot be produced. Some functions return arrays, which appear like a pointer to an object. However, if a function has the option of returning an array , or indicating that a valid array is not possible, it should not return NULL. Instead, the function should return an empty array. Often code that calls a function that returns an array intends merely to iterate over the array elements. In this case, the calling code need not change...iterating change—iterating over the elements works correctly even if the returned array is empty, and thus so the calling code need not check the return value for NULL.

This situation is complicated by the fact that C does not keep track of the length of an array. However, two popular methods have emerged to emulate this behavior. The first is to wrap the array in a struct with an integer storing the length. The second is to place a sentinel value at the end of the data in the array. This second approach is most commonly manifested in null-terminated byte strings (NTBSs).

...

In this noncompliant code example, an inventory system keeps track of the total number of different items (denoted length). Each item is given an index in the array, and the value for that index is the stock of that item. Adding a new item increases length in the struct. Stocking more of an item increases the value for that item's index. For example, if 5 books and 2 erasers were are in stock, the inventory would be stockOfItem[0] = 5 and stockOfItem[1] = 2, assuming books were are index 0 and erasers were are index 1.

The problem arises in this setup when no items are being stocked. getStock would recognize that length = 0 and would return NULL. In this noncompliant code example, erroneous behavior results from getStock returning NULL while main neglects to check for such a value. It results in an abnormal program termination after returning to the main function.

...

This compliant solution correctly returns an empty array in the sortedArray function. If the size of the array is zero0, then sortedArray allocates an array of size 1 and fills it with the sentinel value. It can then successfully return that array to the caller function.

...

Search for vulnerabilities resulting from the violation of this guideline on the CERT website.

...

Bibliography

[Bloch 2008]Item 43, "Return Empty Arrays or Collections, Not Nulls"

 : Return empty arrays or collections, not nulls

...