https://gcc.gnu.org/bugzilla/show_bug.cgi?id=126316
Bug ID: 126316
Summary: Bogus -Wdangling-pointer on variable length arrays in
different scopes in -O2
Product: gcc
Version: 16.1.0
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: c
Assignee: unassigned at gcc dot gnu.org
Reporter: alvinzhang201 at gmail dot com
Target Milestone: ---
The following code produces a -Wdangling-pointer warning when compiled with
`gcc -O2 -Wall` (Godbolt link: https://godbolt.org/z/hzMWMTKPT )
```
void doNothing(char*);
void vla_test( int N ) {
{
char vla[N];
}
char vla2[N];
doNothing(vla2);
}
int main() {
vla_test(4);
}
```
Produces:
```
<source>: In function 'vla_test':
<source>:4:14: warning: unused variable 'vla' [-Wunused-variable]
4 | char vla[N];
| ^~~
In function 'vla_test',
inlined from 'main' at <source>:10:5:
<source>:7:5: warning: using a dangling pointer to 'vla2.7'
[-Wdangling-pointer=]
7 | doNothing(vla2);
| ^~~~~~~~~~~~~~~
<source>:6:10: note: 'vla2.7' declared here
6 | char vla2[N];
| ^~~~
Compiler returned: 0
```
Testing on Godbolt, the warning happens on "x86-64 gcc 12.1" up until "x86-64
gcc 16.1" . Note that -O2 or -O3 needs to be set. Note that changing either
variable-length array (VLA) to normal array removes the warning.
A variant is to add `doNothing(via);` after `char via[N];` . This removes both
warnings on "x86-64 gcc 15.3" and earlier, but -Wdangling-pointer reappears on
"x86-64 gcc 16.1" .
I did a quick check for possible duplicates, and
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=110091 might be related but it's
different. Would be filed under meta-bug
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=104077