False negative: buffer overflow in array parameter

Alejandro Colomar alx@kernel.org
Fri Nov 21 11:24:11 GMT 2025


Hi Chris,

On Thu, Nov 20, 2025 at 09:31:54PM -0600, Chris S wrote:
> Function parameters declared as raw arrays decay to pointer, so it looks
> like an array but isn't.  Maybe the compiler could remember the extent of
> the array before decaying it, but I doubt it does.

The compiler certainly remembers the length of the array.  So much, that
I have a patch for getting said length with _Countof() and it works.
I didn't have to do much for implementing this, as GCC already knows
the length; I only had to tie that with _Countof().

	alx@devuan:~/tmp$ cat countof.c 
	int
	main(int argc, char *argv[argc + 1])
	{
		return _Countof(argv);
	}
	alx@devuan:~/tmp$ /opt/local/gnu/gcc/countof_ap/bin/gcc countof.c 
	alx@devuan:~/tmp$ ./a.out 
	alx@devuan:~/tmp$ echo $?
	2

> The language requires
> this decay, and it's only a quality of implementation request to ask the
> compiler to give a warning for that.  It'd be nice but I'm not holding my
> breath.

I expect GCC to be a very high quality implementation, and diagnose
this.

It already diagnoses things like:

	alx@devuan:~/tmp$ cat arr.c 
	int g(int a[20]);

	int
	f(int a[10])
	{
		return g(a);
	}
	alx@devuan:~/tmp$ gcc -Wall -S arr.c 
	arr.c: In function ‘f’:
	arr.c:6:16: warning: ‘g’ accessing 80 bytes in a region of size 40 [-Wstringop-overflow=]
	    6 |         return g(a);
	      |                ^~~~
	arr.c:6:16: note: referencing argument 1 of type ‘int[20]’
	arr.c:1:5: note: in a call to function ‘g’
	    1 | int g(int a[20]);
	      |     ^


> In the meanwhile, if you're using c++ use std::array and you'll get the
> checking you'd like.

Nah, I'm not using C++.


Have a lovely day!
Alex

-- 
<https://www.alejandro-colomar.es>
Use port 80 (that is, <...:80/>).
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 833 bytes
Desc: not available
URL: <https://gcc.gnu.org/pipermail/gcc-help/attachments/20251121/89745ff9/attachment.sig>


More information about the Gcc-help mailing list