c: Split -Wcalloc-transposed-args warning from -Walloc-size, -Walloc-size fixes
commite7dd72aefed851d11655aa301d6e394ec9805e0d
authorJakub Jelinek <jakub@redhat.com>
Wed, 20 Dec 2023 10:31:18 +0000 (20 11:31 +0100)
committerJakub Jelinek <jakub@redhat.com>
Wed, 20 Dec 2023 10:31:18 +0000 (20 11:31 +0100)
tree72d1ccff1d2bd51c4c3cf7659feff2e4e80bcb7b
parentf5213759a7e0efc4ca7bbb484bab94ca19bc1b5d
c: Split -Wcalloc-transposed-args warning from -Walloc-size, -Walloc-size fixes

The following patch changes -Walloc-size warning to no longer warn
about int *p = calloc (1, sizeof (int));, because as discussed earlier,
the size is IMNSHO sufficient in that case, for alloc_size with 2
arguments warns if the product of the 2 arguments is insufficiently small.

Also, it warns also for explicit casts of malloc/calloc etc. calls
rather than just implicit, so not just
  int *p = malloc (1);
but also
  int *p = (int *) malloc (1);

It also fixes some ICEs where the code didn't verify the alloc_size
arguments properly (Walloc-size-5.c testcase ICEs with vanilla trunk).

And lastly, it introduces a coding style warning, -Wcalloc-transposed-args
to warn for calloc (sizeof (struct S), 1) and similar calls (regardless
of what they are cast to, warning whenever first argument is sizeof and
the second is not).

2023-12-20  Jakub Jelinek  <jakub@redhat.com>

gcc/
* doc/invoke.texi (-Walloc-size): Add to the list of
warning options, remove unnecessary line-break.
(-Wcalloc-transposed-args): Document new warning.
gcc/c-family/
* c.opt (Wcalloc-transposed-args): New warning.
* c-common.h (warn_for_calloc, warn_for_alloc_size): Declare.
* c-warn.cc (warn_for_calloc, warn_for_alloc_size): New functions.
gcc/c/
* c-parser.cc (c_parser_postfix_expression_after_primary): Grow
sizeof_arg and sizeof_arg_loc arrays to 6 elements.  Call
warn_for_calloc if warn_calloc_transposed_args for functions with
alloc_size type attribute with 2 arguments.
(c_parser_expr_list): Use 6 instead of 3.
* c-typeck.cc (build_c_cast): Call warn_for_alloc_size for casts
of calls to functions with alloc_size type attribute.
(convert_for_assignment): Likewise.
gcc/testsuite/
* gcc.dg/Walloc-size-4.c: New test.
* gcc.dg/Walloc-size-5.c: New test.
* gcc.dg/Wcalloc-transposed-args-1.c: New test.
gcc/c-family/c-common.h
gcc/c-family/c-warn.cc
gcc/c-family/c.opt
gcc/c/c-parser.cc
gcc/c/c-typeck.cc
gcc/doc/invoke.texi
gcc/testsuite/gcc.dg/Walloc-size-4.c [new file with mode: 0644]
gcc/testsuite/gcc.dg/Walloc-size-5.c [new file with mode: 0644]
gcc/testsuite/gcc.dg/Wcalloc-transposed-args-1.c [new file with mode: 0644]