Bug 84544 - Missing warning when returning a reference to internal variable inside a lambda
Summary: Missing warning when returning a reference to internal variable inside a lambda
Status: NEW
Alias: None
Product: gcc
Classification: Unclassified
Component: c++ (show other bugs)
Version: 7.2.0
: P3 enhancement
Target Milestone: ---
Assignee: Not yet assigned to anyone
URL:
Keywords: c++-lambda, diagnostic
: 90647 (view as bug list)
Depends on:
Blocks: Wreturn-local-addr lambdas
  Show dependency treegraph
 
Reported: 2018-02-24 21:34 UTC by Jussi Pakkanen
Modified: 2023-12-30 02:20 UTC (History)
5 users (show)

See Also:
Host:
Target:
Build:
Known to work:
Known to fail:
Last reconfirmed: 2021-12-17 00:00:00


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description Jussi Pakkanen 2018-02-24 21:34:31 UTC
Suppose you have a C++14 method like this:

auto f1() {
    int x = 3;
    auto l = [&]() -> int& { return x; };
    return l;
}

Here the returned lambda contains a reference to the stack allocated integer that goes out of scope. Gcc does not give a warning for this. If you call function f1 like this:

int& f2() {
    auto l = f1();
    return l();
}

Then Gcc does print the following warning (but only with -O2 or higher):

<source>: In function 'int& f2()':
<source>:9:14: warning: function returns address of local variable [-Wreturn-local-addr]
     return l();
              ^
<source>:2:9: note: declared here
     int x = 3;
         ^
Compiler returned: 0

It would be useful if gcc generated a warning for f1 already.
Comment 1 Andrew Pinski 2021-12-17 03:27:32 UTC
I have seen something similar too.

Confirmed.
Comment 2 Andrew Pinski 2021-12-17 03:29:11 UTC
*** Bug 90647 has been marked as a duplicate of this bug. ***
Comment 3 Martin Sebor 2022-01-16 00:44:26 UTC
This should be easily detectable even without optimization by the new -Wdangling-pointer.  I think it's essentially equivalent to the following test case:

$ cat t.C && gcc -S -Wall -fdump-tree-waccess1=/dev/stdout t.C
struct A
{
  int &r;
};

A f ()
{
  int x = 0;
  return A{ x };
}

;; Function f (_Z1fv, funcdef_no=0, decl_uid=2373, cgraph_uid=1, symbol_order=0)
...
struct A f ()
{
  int x;
  struct A D.2386;

  <bb 2> :
  x = 0;
  D.2386.r = &x;     <<< not handled by -Wdangling-pointer
  x ={v} {CLOBBER};

  <bb 3> :
<L1>:
  return D.2386;     <<<

}