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

Leander Besting via cfe-dev cfe-dev at lists.llvm.org
Mon Aug 16 10:19:45 PDT 2021


The following doesn't produce any warnings but I don't know about clang-tidy.

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

// a.c
#include <stdlib.h>
struct S {
    int x, y, z;
};
int main() {
    // sizeof (struct S) == 12
    // sizeof (s) == 8
    struct S *s = malloc(sizeof(struct S) * 2);
    free(s);
}

‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐

On Monday, August 16th, 2021 at 19:03, Joerg Sonnenberger via cfe-dev <cfe-dev at lists.llvm.org> wrote:

> On Mon, Aug 16, 2021 at 03:48:54PM +0000, Keane, Erich via cfe-dev wrote:
>
> > 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.
>
> It depends. The former is certainly valid and common, but the latter
>
> should only be valid if the last member is a (flexible) array. There are
>
> certainly levels of quality here.
>
> Does clang-tidy or clang-analyze complain about multiplicative arguments
>
> in general? E.g. malloc(sizeof(S) * len) ?
>
> Joerg
>
> 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