Description
Bugzilla Link | 17418 |
Version | 3.3 |
OS | All |
Reporter | LLVM Bugzilla Contributor |
Extended Description
With -Weverything enabled, the following code does not generate a warning:
-------------------------- Cut Here ----------------------------
#include <stdlib.h>
int main() {
int *x;
x = malloc(sizeof(char));
return 0;
}
-------------------------- Cut Here ----------------------------
$ clang -std=c11 -Weverything -g -O -c warn.c
$
Under gcc, a warning can be produced if -Wc++-compat is enabled:
$ gcc -Wc++-compat -g -O -c warn.c
warn.c: In function 'main':
warn.c:7: warning: request for implicit conversion from 'void *' to 'int *' not permitted in C++
Gcc's reason for emitting the warning is that casting from void * to another pointer type is allowed in C, but is forbidden in C++.
However, this practice is widely discouraged in C as well, due to the possibility of disaster (as shown in the example above). E.g. see CERT's recommendation that the result of malloc should always be immediately cast:
In Gcc this warning must be individually enabled, it is not part of -Wall -Wextra or -pedantic.
The same behavior for clang would be highly desirable, as although this allows the compiler to catch errors, for every site where explicitly casting void* is required, there is another site where casting the result of malloc is verboten to avoid hiding the case stdlib.h wasn't included. (A strong argument can be made that adding a warning won't affect the latter site since even -Wall already generates a warning for omitting stdlib.h in that case.)
Hence a -Wimplicit-void-cast flag that generates warnings in this case would be a welcome addition to the clang frontend, particularly if feature-parity with GCC's -Wc++-compat flag is not desirable for other reasons.
Thank you for your consideration!