www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - Returning a reference to a local variable

reply Arcane Jill <Arcane_member pathlink.com> writes:
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
Jul 20 2004
next sibling parent "Kris" <someidiot earthlink.dot.dot.dot.net> writes:
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

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


 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

Jul 20 2004
prev sibling parent Derek Parnell <derek psych.ward> writes:
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
Jul 20 2004