Thread overview
Returning a reference to a local variable
Jul 20, 2004
Arcane Jill
Jul 20, 2004
Kris
Jul 20, 2004
Derek Parnell
July 20, 2004
In the manual (on page http://www.digitalmars.com/d/function.html) it says:

> "It is an error to return the address of or a reference to a local variable."

And quite right, too. This, then, is a compiler bug.

#    char[] f()
#    {
#        char[5] s = "hello";
#        return s;
#    }
#
#    void main()
#    {
#        printf("s = \"%s\"\n", f());
#    }

Access Violation

Arcane Jill


July 20, 2004
Jill: your access violation is likely due to the %s in the printf (should be %.*s instead). That aside, you're absolutely right that the compiler should attempt to trap this kind of thing ~ there's no clear benefit in letting it compile successfully. I guess it's a question of priorities.


"Arcane Jill" <Arcane_member@pathlink.com> wrote in message news:cdih8m$17h9$1@digitaldaemon.com...
> In the manual (on page http://www.digitalmars.com/d/function.html) it
says:
>
> > "It is an error to return the address of or a reference to a local
variable."
>
> And quite right, too. This, then, is a compiler bug.
>
> #    char[] f()
> #    {
> #        char[5] s = "hello";
> #        return s;
> #    }
> #
> #    void main()
> #    {
> #        printf("s = \"%s\"\n", f());
> #    }
>
> Access Violation
>
> Arcane Jill
>
>


July 20, 2004
On Tue, 20 Jul 2004 07:23:02 +0000 (UTC), Arcane Jill wrote:

> In the manual (on page http://www.digitalmars.com/d/function.html) it says:
> 
>> "It is an error to return the address of or a reference to a local variable."
> 
> And quite right, too. This, then, is a compiler bug.
> 
> #    char[] f()
> #    {
> #        char[5] s = "hello";
> #        return s;
> #    }
> #
> #    void main()
> #    {
> #        printf("s = \"%s\"\n", f());
> #    }
> 
> Access Violation
> 

As Walter is philosophically against warnings, and returning such an address is only an *error* if you try to dereference it, then it is consistant that D allows the coder to potentially do something stupid.

BTW, the access violation is because you used "%s" rather than "%.*s".

-- 
Derek
Melbourne, Australia
20/Jul/04 6:11:30 PM