https://gcc.gnu.org/g:0b402dd400473d0c538e07c6609152ce606d8683
commit r14-12934-g0b402dd400473d0c538e07c6609152ce606d8683 Author: Jakub Jelinek <[email protected]> Date: Wed Oct 7 10:20:58 2026 +0200 c++: Suppress -Walloc-size warnings for allocations from new expressions The new expression lowering should always ensure that the allocation size corresponds properly to the allocated object (or throws/returns null on overflow). So the -Walloc-size warning is kind of useless for that. For uses of new the size really should already match what we are allocating, for array new it can be 0 if we allocate 0 elements (and where -Walloc-size was currently triggering). 2026-10-07 Jakub Jelinek <[email protected]> * cp-gimplify.cc (cp_genericize_r): Don't call warn_for_alloc_size for CALL_FROM_NEW_OR_DELETE_P calls. * g++.dg/warn/Walloc-size-2.C: New test. Reviewed-by: Jason Merrill <[email protected]> (cherry picked from commit a343bd9078c13feb7522ea58501449c2cc8ad3f4) Diff: --- gcc/cp/cp-gimplify.cc | 5 ++++- gcc/testsuite/g++.dg/warn/Walloc-size-2.C | 21 +++++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/gcc/cp/cp-gimplify.cc b/gcc/cp/cp-gimplify.cc index 845243edbd0d..eac4dafad2ba 100644 --- a/gcc/cp/cp-gimplify.cc +++ b/gcc/cp/cp-gimplify.cc @@ -2094,9 +2094,12 @@ cp_genericize_r (tree *stmt_p, int *walk_subtrees, void *data) *stmt_p = predeclare_vla (*stmt_p); /* Warn of new allocations that are not big enough for the target - type. */ + type. Don't warn for calls from new expressions, new TYPE[0] + is fine and new expansion should arrange for the right size + to be provided. */ if (warn_alloc_size && TREE_CODE (TREE_OPERAND (stmt, 0)) == CALL_EXPR + && !CALL_FROM_NEW_OR_DELETE_P (TREE_OPERAND (stmt, 0)) && POINTER_TYPE_P (TREE_TYPE (stmt))) { if (tree fndecl = get_callee_fndecl (TREE_OPERAND (stmt, 0))) diff --git a/gcc/testsuite/g++.dg/warn/Walloc-size-2.C b/gcc/testsuite/g++.dg/warn/Walloc-size-2.C new file mode 100644 index 000000000000..3e49b6bb45a1 --- /dev/null +++ b/gcc/testsuite/g++.dg/warn/Walloc-size-2.C @@ -0,0 +1,21 @@ +// Tests the warnings for insufficient allocation size. +// { dg-do compile } +// { dg-options "-Walloc-size" } + +struct S { int x[10]; }; +void bar (S *); + +void +foo (void) +{ + S *p = new S[0]; + char *q = new char[0]; + S *r = (S *) ::operator new[] (0); // { dg-warning "allocation of insufficient size '0' for type 'S' with size '\[0-9]\+'" } + char *t = (char *) ::operator new[] (0); // { dg-warning "allocation of insufficient size '0' for type 'char' with size '1'" } + S *u = (S *) ::operator new[] (1); // { dg-warning "allocation of insufficient size '1' for type 'S' with size '\[0-9]\+'" } + ::operator delete[] (u); + ::operator delete[] (t); + ::operator delete[] (r); + delete[] q; + delete[] p; +}
