I was wondering if you could tell me when you are able to return NULL
, as the result of a function in C.
For instance int lenght()
can\'t retur
It is a matter of convention and you should clearly have one in your head and document it (at least in comments).
Sometimes a pointer really should always point to a valid address (see this intSwap
example, both arguments should be valid pointers). At other times, it should either be such a valid address, or be NULL
. Conceptually the pointer type is then by convention a sum type (between genuine pointer addresses and the special NULL
value).
Notice that the C language does not have a type (or a notation) which enforces that some given pointer is always valid and non-null. BTW, with GCC specifically, you can annotate a function with __attribute__
using nonnull
to express that a given argument is never null.
A typical example is FILE*
pointers in fopen
function is documented to be able to return NULL
(on failure), or some valid pointer. But the fprintf
function is expecting a valid pointer (and passing NULL
to it as the first argument is some undefined behavior, often a segmentation fault; and UB is really bad).
Some non-portable programs even use several "special" pointer values (which should not be dereferenced), e.g. (on Linux/x86-64) #define SPECIAL_SLOT (void*)((intptr_t)-1)
(which we know that on Linux it is never a valid address). Then we could have the convention that a pointer is a valid pointer to a valid memory zone, or NULL
or SPECIAL_SLOT
(hence, if seen as an abstract data type, it is a sum type of two distinct invalid pointers NULL
and SPECIAL_SLOT
and the set of valid addresses). Another example is MAP_FAILURE
as result of mmap(2) on Linux.
BTW, when using pointers in C to heap allocated data (indirectly obtained with malloc
), you also need conventions about who is in charge of releasing the data (by using free
, often thru a supplied function to free a data and all its internal stuff).
Good C programming requires many explicit conventions regarding pointers, and it is essential to understand them precisely and document them well. Look for example[s] into GTK. Read also about restrict.