https://gcc.gnu.org/bugzilla/show_bug.cgi?id=128075
Bug ID: 128075
Summary: wrong code at -O1 and above when a nested function
returns the address of a local of its containing
function
Product: gcc
Version: 17.0
Status: UNCONFIRMED
Keywords: wrong-code
Severity: normal
Priority: P3
Component: tree-optimization
Assignee: unassigned at gcc dot gnu.org
Reporter: kyuwoncho18 at gmail dot com
Target Milestone: ---
Target: x86_64-pc-linux-gnu
int outer(void)
{
int x = 1;
__attribute__((noinline)) int *g(void) { return &x; }
int *p = g();
*p = 5;
return x;
}
int main(void)
{
if (outer() != 5)
__builtin_abort();
}
godbolt: https://godbolt.org/z/voe9bKxf3
g returns &x, so *p = 5 sets x and outer must return 5. With -O0, or -O2
-fno-tree-sra, the program exits normally; with -O1, -O2, -O3 or -Os outer
returns 1 and the program aborts.