[cfe-dev] Clang doesn't warn about wrong sized mallocs

Artem Dergachev via cfe-dev cfe-dev at lists.llvm.org
Mon Aug 16 08:40:35 PDT 2021


We do have an on-by-default static analyzer warning for this:


     $ clang test.c --analyze --analyzer-output text

     test.c:8:19: warning: Result of 'malloc' is converted to a pointer 
of type 'struct S', which is incompatible with sizeof operand type 
'struct S *' [unix.MallocSizeof]
         struct S *s = malloc(sizeof(s));
         ~~~~~~~~~~    ^~~~~~ ~~~~~~~~~


Or same with clang-tidy:

     $ clang-tidy -checks='clang-analyzer-unix.MallocSizeof' test.c

     test.c:8:19: warning: Result of 'malloc' is converted to a pointer 
of type 'struct S', which is incompatible with sizeof operand type 
'struct S *' [clang-analyzer-unix.MallocSizeof]
         struct S *s = malloc(sizeof(s));
         ~~~~~~~~~~    ^~~~~~ ~~~~~~~~~


I agree this probably should be a compiler warning; malloc() is as 
standard as a function can get so it's probably ok for the compiler to 
recognize and treat specially(?)

On 8/14/21 6:59 AM, Leander Besting via cfe-dev wrote:
> The following code does not produce a warning when compiled with clang 12.0.1 and -Weverything despite there being an obvious error. It should be pretty trivial to detect that the argument to malloc does not match the size that s expects to point to, similar to how printf arguments are checked.
>
> #include <stdlib.h>
> struct S {
>      int x, y, z;
> };
> int main() {
>      // sizeof (struct S) == 12
>      // sizeof (s) == 8
>      struct S *s = malloc(sizeof(s));
> }
>
> $ clang --version
> clang version 12.0.1
> Target: x86_64-pc-linux-gnu
> Thread model: posix
> InstalledDir: /usr/bin
>
> --
> Leander Besting
> _______________________________________________
> cfe-dev mailing list
> cfe-dev at lists.llvm.org
> https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-dev



More information about the cfe-dev mailing list