Skip to content

No warning for implicit void* cast #17792

Closed
@llvmbot

Description

@llvmbot
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:

https://www.securecoding.cert.org/confluence/display/seccode/MEM02-C.+Immediately+cast+the+result+of+a+memory+allocation+function+call+into+a+pointer+to+the+allocated+type

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!

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugzillaIssues migrated from bugzillacclang:diagnosticsNew/improved warning or error message in Clang, but not in clang-tidy or static analyzerenhancementImproving things as opposed to bug fixing, e.g. new or missing feature

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions