On 10/6/26 9:06 AM, Jakub Jelinek wrote:
Hi!
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).
Bootstrapped/regtested on x86_64-linux and i686-linux, ok for trunk?
OK.
2026-10-06 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.
--- a/gcc/cp/cp-gimplify.cc 2026-09-14 18:09:16.043956582 +0200
+++ b/gcc/cp/cp-gimplify.cc 2026-10-05 13:31:26.503989083 +0200
@@ -2391,9 +2391,12 @@ cp_genericize_r (tree *stmt_p, int *walk
*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)))
--- a/gcc/testsuite/g++.dg/warn/Walloc-size-2.C 2026-10-05 13:15:11.565194328
+0200
+++ b/gcc/testsuite/g++.dg/warn/Walloc-size-2.C 2026-10-05 13:33:00.014722749
+0200
@@ -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;
+}
Jakub