Chris Tetreault via llvm-dev
2021-Aug-16 17:11 UTC
[llvm-dev] [cfe-dev] Clang doesn't warn about wrong sized mallocs
A valid use for `malloc(sizeof(Foo) + c)` could be if one were writing a custom allocation function. They might be cramming metadata in that trailing area after the space for `Foo`. -----Original Message----- From: cfe-dev <cfe-dev-bounces at lists.llvm.org> On Behalf Of Joerg Sonnenberger via cfe-dev Sent: Monday, August 16, 2021 10:03 AM To: cfe-dev at lists.llvm.org Subject: Re: [cfe-dev] Clang doesn't warn about wrong sized mallocs WARNING: This email originated from outside of Qualcomm. Please be wary of any links or attachments, and do not enable macros. 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
Joerg Sonnenberger via llvm-dev
2021-Aug-16 21:46 UTC
[llvm-dev] [cfe-dev] Clang doesn't warn about wrong sized mallocs
On Mon, Aug 16, 2021 at 05:11:28PM +0000, Chris Tetreault wrote:> A valid use for `malloc(sizeof(Foo) + c)` could be if one were writing > a custom allocation function. They might be cramming metadata in that > trailing area after the space for `Foo`.Sure, but that is better written by introducing a local Foo_wrap type that starts with a Foo member. That way it is both clearer to the reader what is intended and ensures correct alignment etc. Joerg