Re: False negative: buffer overflow in array parameter
Alejandro Colomar via Gcc-help <[email protected]>
| Newsgroups | gmane.comp.gcc.help |
|---|---|
| Message-ID | <4uhpgxve4brp6qwtno2r3n3y3hlgg5j4ff24qr35mtzcjzkkks@kevbsodf4ic3> |
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/>).
signature.asc
(application/pgp-signature, 833 B)
-----BEGIN PGP SIGNATURE----- iQIzBAABCgAdFiEES7Jt9u9GbmlWADAi64mZXMKQwqkFAmkgS9sACgkQ64mZXMKQ wqkBRhAAr4gs/GVKvnldiDu9Ir+H8/gMUu8NxRm5Fgk696UmCcLxsWrg6hYLTKOm FgP2XeKBXvnH/3qIww785Q/RlYNuJqKa1nRlJayqkGPTewaqBsVmNQkLtF34kGtT vt/1uj1XOj/STIpRUc4o0vlEoHn+dj9OnBQc/5Su+DhogJiuMtmS0DCkaeh+/jpt RgdaWqTVQS2otpfARq/L+Vk2FIU9uDEwPxBEe3N7Vx91O1JAdwBa4RMUN9ny3lPZ WTBcJK4qrrGsDYVtnGOjbsqKVDSw2fIjdbynZ2L0rK5gCB4MmBlw2sKirNUOs6Aj ZbbEwyqW/6VscQfs/wLPKV043n6LfWlRWI20Pd47aYO7T8uH2XJkVR/SyE89gly4 lRrf7ihafS8OtFbA4lGe1TnPAbUZtSUXi0XMxaK9+sNul3Zv06TJi4izP5COdJDT 3Uk+tCBAa/SXaK/OLvUdlga6dNSEXDephlbzzlbXYplbFlhEt1oYEO7+xb8nvTeO t7/XoFQgWIzdGjUUCJIpRIklrTy6fTURxnBsXFLopndFO6z839l6CTiLpkeqU+ud 4RW5/y5HBs4lNP4rHcW0mtcRpuxKR4bA6veY8Sv3kyvj4HR5UZc8wWosuGDNO+Iz 9pDwZJgKDotMV/+KDCMbuSx6kH2oTIFVjgC23Mv9bAqTDIYcJxY= =Cg2p -----END PGP SIGNATURE-----