[cfe-dev] Clang doesn't warn about wrong sized mallocs
Joerg Sonnenberger via cfe-dev
cfe-dev at lists.llvm.org
Mon Aug 16 14:51:08 PDT 2021
On Mon, Aug 16, 2021 at 05:19:45PM +0000, Leander Besting wrote:
> 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);
> }
This is fine, because the compiler can statically assert that no
overflow can happen. But the following IMO should have a warning:
#include <stdlib.h>
struct S {
int x, y, z;
};
size_t len;
int main() {
struct S *s = malloc(sizeof(struct S) * len);
free(s);
}
At least for the static analyzer. It's a very common category of bugs.
Joerg
More information about the cfe-dev
mailing list