[Bug c/71219] Warn about (struct S*)malloc(n) where n < sizeof(struct S)

redi at gcc dot gnu.org gcc-bugzilla@gcc.gnu.org
Tue Nov 10 17:31:15 GMT 2020


https://gcc.gnu.org/bugzilla/show_bug.cgi?id=71219

Jonathan Wakely <redi at gcc dot gnu.org> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
   Last reconfirmed|2016-05-26 00:00:00         |2020-11-10

--- Comment #4 from Jonathan Wakely <redi at gcc dot gnu.org> ---
Complete testcase:

#include <stdlib.h>

struct S1 {
  unsigned int x;
  float        y;
  struct S1   *z;
};


struct S1 *f1(void) {
  struct S1 *p = malloc(sizeof(p));  // diagnostic required
  return p;
}


It would probably make sense to not only warn for malloc, but also for other
functions with __attribute__((malloc)) and __attribute__((alloc_size(n))) where
n!=sizeof(*p). That would also help for xmalloc and similar wrappers in gcc and
glibc.


More information about the Gcc-bugs mailing list