diff options
author | Martin Uecker <uecker@tugraz.at> | 2023-07-27 13:36:05 +0200 |
---|---|---|
committer | Martin Uecker <uecker@tugraz.at> | 2023-11-01 22:35:14 +0100 |
commit | d880e093d92084f55b10626610ef059fd9194a6a (patch) | |
tree | 7d70dae90a63ba18a24e8f89ebeed7e1af246baf /gcc/c | |
parent | 25f92179dea3080788c83743823c1decd84fee23 (diff) | |
download | gcc-d880e093d92084f55b10626610ef059fd9194a6a.zip gcc-d880e093d92084f55b10626610ef059fd9194a6a.tar.gz gcc-d880e093d92084f55b10626610ef059fd9194a6a.tar.bz2 |
c: Add Walloc-size to warn about insufficient size in allocations [PR71219]
Add option Walloc-size that warns about allocations that have
insufficient storage for the target type of the pointer the
storage is assigned to. Added to Wextra.
PR c/71219
gcc:
* doc/invoke.texi: Document -Walloc-size option.
gcc/c-family:
* c.opt (Walloc-size): New option.
gcc/c:
* c-typeck.cc (convert_for_assignment): Add warning.
gcc/testsuite:
* gcc.dg/Walloc-size-1.c: New test.
* gcc.dg/Walloc-size-2.c: New test.
Diffstat (limited to 'gcc/c')
-rw-r--r-- | gcc/c/c-typeck.cc | 28 |
1 files changed, 28 insertions, 0 deletions
diff --git a/gcc/c/c-typeck.cc b/gcc/c/c-typeck.cc index 0de4662..16fadfb 100644 --- a/gcc/c/c-typeck.cc +++ b/gcc/c/c-typeck.cc @@ -7347,6 +7347,34 @@ convert_for_assignment (location_t location, location_t expr_loc, tree type, "request for implicit conversion " "from %qT to %qT not permitted in C++", rhstype, type); + /* Warn of new allocations that are not big enough for the target + type. */ + tree fndecl; + if (warn_alloc_size + && TREE_CODE (rhs) == CALL_EXPR + && (fndecl = get_callee_fndecl (rhs)) != NULL_TREE + && DECL_IS_MALLOC (fndecl)) + { + tree fntype = TREE_TYPE (fndecl); + tree fntypeattrs = TYPE_ATTRIBUTES (fntype); + tree alloc_size = lookup_attribute ("alloc_size", fntypeattrs); + if (alloc_size) + { + tree args = TREE_VALUE (alloc_size); + int idx = TREE_INT_CST_LOW (TREE_VALUE (args)) - 1; + /* For calloc only use the second argument. */ + if (TREE_CHAIN (args)) + idx = TREE_INT_CST_LOW (TREE_VALUE (TREE_CHAIN (args))) - 1; + tree arg = CALL_EXPR_ARG (rhs, idx); + if (TREE_CODE (arg) == INTEGER_CST + && INTEGER_CST == TREE_CODE (TYPE_SIZE_UNIT (ttl)) + && tree_int_cst_lt (arg, TYPE_SIZE_UNIT (ttl))) + warning_at (location, OPT_Walloc_size, "allocation of " + "insufficient size %qE for type %qT with " + "size %qE", arg, ttl, TYPE_SIZE_UNIT (ttl)); + } + } + /* See if the pointers point to incompatible address spaces. */ asl = TYPE_ADDR_SPACE (ttl); asr = TYPE_ADDR_SPACE (ttr); |