In C currently, pointers just are, and there are no qualifiers to tell programmers whether they can be null or not. Objective-C kind of solves this problem by adding _Nonnull
and _Nullable
. However these hints do not really do much besides raise compiler warnings in only a few of the many possible misuse cases.
I would like to add a stronger nonnull
keyword to my C-style programming language (no nullable
counterpart because nullable
is just designated by the absence of nonnull
). The behavior is simple: NULL
is a trap representation for nonnull
pointers. That is, if a pointer qualified with nonnull
contains NULL
and is read, immediate undefined behavior is invoked. Compilers would warn if a non nonnull
pointer is dereferenced, because then NULL
might be being dereferenced (also undefined behavior). This could prevent common mistakes such as not checking malloc()
/fopen()
for NULL
, and also help avoid redundant checks on pointers that will already never be NULL
.
What are the semantic options for users to convert a non nonnull
to a nonnull
? A basic option would be:
void *ptr = malloc(size);
if (ptr) {
void *nonnull nnptr = ptr; // Conversion is valid because the code is unreachable if ptr is NULL
}
However, a dumb compiler may still warn at this, and this still creates redundant variables. There needs to be a syntactic way to 'convert' regular to nonnull
in a way that is ergonomic and can be correctly and easily checked by the compiler. What are my options?
nonnull
is UB. Then your compiler can implement a runtime check. But checking at compile time is (afaik) not possible in general $\endgroup$23
to a string variable if it finds a counterexample to Fermat's last theorem; this program is type-safe, but all real type-checkers reject it. $\endgroup$