Bug 70121 - Spurious warning and crash when returning a reference from lambda
Summary: Spurious warning and crash when returning a reference from lambda
Status: RESOLVED DUPLICATE of bug 53157
Alias: None
Product: gcc
Classification: Unclassified
Component: c++ (show other bugs)
Version: 5.3.1
: P3 normal
Target Milestone: 7.0
Assignee: Not yet assigned to anyone
URL:
Keywords: wrong-code
Depends on:
Blocks:
 
Reported: 2016-03-07 12:30 UTC by blastrock
Modified: 2016-04-27 14:19 UTC (History)
3 users (show)

See Also:
Host:
Target:
Build:
Known to work:
Known to fail:
Last reconfirmed: 2016-03-07 00:00:00


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description blastrock 2016-03-07 12:30:22 UTC
When I try to compile this simple program with gcc 5.3.1:

    #include <functional>
    int main(int argc, char *argv[])
    {
      const int val = 28;
      auto ff = [&]() -> const int& { return val; };
      int i = ff();
    }

with the argument -std=c++11, I get the following warning:

    warning: returning reference to temporary [-Wreturn-local-addr]

And the program crashes on the int assign statement.

I believe this code is legal, the temporary variable is still valid when the lambda is called. And the same code compiles without warning and runs without crash with clang 3.7.
Comment 1 Marc Glisse 2016-03-07 14:24:49 UTC
The wrong warning is old, but since gcc-5 we reuse that warning code to change the return to null, which makes the issue much worse.
Comment 2 Patrick Palka 2016-03-10 20:04:25 UTC
I think I have a patch.
Comment 3 Patrick Palka 2016-03-10 23:05:29 UTC
A candidate patch posted at: https://gcc.gnu.org/ml/gcc-patches/2016-03/msg00669.html
Comment 4 Jason Merrill 2016-03-18 15:14:11 UTC
The temporary it mentions is a temporary generated within the lambda to hold the value "28", because we (wrongly) immediately decay the use of 'val' to its constant value, so the temporary is out of scope after the lambda returns.  Returning null doesn't seem worse to me, rather it will help people catch undefined behavior more rapidly.  This is an important bug, certainly, but I don't think it's a regression.
Comment 5 Patrick Palka 2016-03-18 15:32:52 UTC
Removing regression markers.
Comment 6 Jakub Jelinek 2016-03-18 15:38:45 UTC
The regression markers should stay if it is a regression.
Comment 7 Patrick Palka 2016-03-18 15:59:19 UTC
But as Jason said in comment #4, (IIUC) the test case never compiled correctly in any gcc version.  It was marked a regression only because -Wreturn-local-addr now deliberately returns null but arguably that's not a regression either.
Comment 8 Jakub Jelinek 2016-03-18 16:00:06 UTC
Sorry, missed that comment.
Comment 9 Patrick Palka 2016-04-27 14:19:48 UTC
Looks like this is a dup of PR c++/53157.

*** This bug has been marked as a duplicate of bug 53157 ***