Explicit non-null pointers in C
Browsing this thread on Stack Overflow, I discovered a lesser-known feature of C that allows you to explicitly declare that a particular array must contain at least some number of elements. Consider the following piece of unsafe code:
If the goal were to be nasty, I’d just have to try and poison this function with a NULL
pointer and the application would cause a segfault. Actually, for a long time I thought that code written in C was destined to be vulnerable to these kinds of mistakes.
However, as I found out, with C99 you can actually hint the compiler that the pointer must be non-NULL
. How? C has support for function arguments to contain the static
keyword inside the array descriptor part, which specifies the minimum number of elements which the array should be. Here's an example from the thread:
This actually means the argument array, inputval
, must be at least 4 elements large. This language feature helps us because arrays and pointers share special equivalence in C, so we can fix up our vulnerable function above like so (full working example):
But if we now try and insert some nasty code we get a warning:
Unfortunately, it’s not all that smart. We can circumvent both gcc and clang quite easily by just assigning a local to NULL
and passing it:
It does offer some protection against incorrect NULL
ing of non-optional pointer parameters, though.