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

Keane, Erich via cfe-dev cfe-dev at lists.llvm.org
Mon Aug 16 08:48:54 PDT 2021


I think the only valid thing to check here is allocated 'smaller', since:

struct S *s = malloc(sizeof(struct S) * 10); // An array
struct S *s2 = malloc(sizeof(struct S) + 5); // a struct with some level of trailing storage, shows that multiple-of isn't sufficient

are both valid/reasonably common uses of malloc.


-----Original Message-----
From: cfe-dev <cfe-dev-bounces at lists.llvm.org> On Behalf Of Artem Dergachev via cfe-dev
Sent: Monday, August 16, 2021 8:41 AM
To: Leander Besting <leander_bes at protonmail.ch>; cfe-dev at lists.llvm.org
Subject: Re: [cfe-dev] Clang doesn't warn about wrong sized mallocs

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

_______________________________________________
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