3 ms·
Try as I might I can't get gcc to produce warnings for this (invocation: gcc --std=c99 -Wall -Werror -Wpedantic -Wnonnull). I can get clang to do so however.
by adrusi 8y ago
Try as I might I can't get gcc to produce warnings for this (invocation: gcc --std=c99 -Wall -Werror -Wpedantic -Wnonnull). I can get clang to do so however.
I didn't expect to get any compiler warnings for code that passes NULL to a [static 1] parameter, so I wasn't surprised when this code compiled silently:
#include <stdio.h>
void end(int foo[static 1]) {
printf("%d\n", *foo);
}
void middle(int *foo) {
end(foo);
}
int main() {
middle(NULL);
return 0;
}
But I was a bit disappointed that the following compiled without warning as well:
#include <stdio.h>
void end(int foo[static 1]) {
printf("%d\n", *foo);
}
int main() {
int *foo = NULL;
end(foo);
return 0;
}
- rwmj 8y agoGCC has an extension __attribute__((nonnull)) which is probably better if you want to ensure that NULL is not passed as a function parameter. https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#Common-Function-Attributes https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attribute... According to this document it also allows the compiler to make extra optimizations: http://rachid.koucha.free.fr/tech_corner/nonnull_gcc_attribute.html http://rachid.koucha.free.fr/tech_corner/nonnull_gcc_attribu...
- eliasdaler 8y agoThat's because the compiler would have to track at compile time which value the "foo" has.
- astrobe_ 8y agoThat's what I was afraid of, the feature is "incomplete" in my eyes, because one would expect the compiler to be "smart enough" to catch this case. A feature such like this that has an unclear perimeter is of little use. Well, I guess that this feature has a precise definition in the C spec, but one should note that the purpose half of the warnings the compiler emits (guesstimate) is to mitigate the imperfect knowledge of the C spec. Typical example is operator precedence: who can remember 17 levels of precedence? One can remember the obvious cases, one can remember the less obvious case if one uses them often enough, but anything besides that (and when in doubt when you trying to figure out where a bug comes from), one just says "fack it" and put parenthesis everywhere. Smalltalk, APL, Lisp, Forth were quite right to sacrifice natural expressions notations for something more useful than being kind with beginners. An unnatural but simpler model is better than a natural but more complex model, because programmers are not compilers. This is a fact that compiler/language designers seem to forget sometimes. So it's not surprise to me that this feature is little known: it's not reliable.
- anilakar 8y agoIIRC GCC doesn't warn you but Clang does. Looks like the decade-old rule of thumb "use Clang for development and GCC for production" still applies.