[cfe-dev] Undiagnosed "reference to stack memory [...] returned"

Matthieu Monrocq matthieu.monrocq at gmail.com
Wed Sep 15 12:58:03 PDT 2010


I don't think it could get extended either.

I must admit I don't know much about compilers, but naively I would say in
order to implement this lifetime extension that the standard mandates, I
would examine the signature of get_value(), which returns an int, and
allocate enough space for an int on the stack (instead of a const reference)
while treating it a const reference to an int for the purpose of compilation
(it cannot be modified). That's the only trick I can think of short of
allocating this on the heap... and this would be a performance killer.

However the caller of get_reference_no_warning() or
get_reference_no_warning_2() expects a const reference, and thus is unlikely
to prepare the stack for a copy instead (just in case). While it could
possibly be done with an inline function, it would get hairy as soon as the
function is defined in another translation unit.

Therefore it seems that the proper thing to do would be to diagnose the
issue (in both get_reference_no_warning cases) and let the developer fix
them. I surmise it should be possible to detect them (since VC++ already
detects the first case), but then, as I said, I am very naive about
compilers yet.

I hope to look at this further during the week-end, guess it would be as
good a way as any to try and understand how Clang work

For reference I fixed such an issue today in real code (compiled with gcc
3.4.2), and it had gone undiagnosed too (and generated some mess because it
was a string instead of an int...).

- Matthieu

2010/9/15 Eli Friedman <eli.friedman at gmail.com>

> On Wed, Sep 15, 2010 at 11:32 AM, Ted Kremenek <kremenek at apple.com> wrote:
> > I'm not certain this is a bug.  The 'const int&' causes the lifetime of
> the object returned from get_value() to be extended to its last use.  Does
> this extend to the caller of get_reference_no_warning_2() since that also
> returns a const reference?
>
> In get_reference_no_warning_2, w2 is bound to a temporary which is
> live for the lifetime of w2; returning a reference to the temporary
> doesn't extend its lifetime.
>
> -Eli
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/cfe-dev/attachments/20100915/bf8c6cce/attachment.html>


More information about the cfe-dev mailing list