Thread overview | |||||
---|---|---|---|---|---|
|
July 20, 2004 Returning a reference to a local variable | ||||
---|---|---|---|---|
| ||||
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 Re: Returning a reference to a local variable | ||||
---|---|---|---|---|
| ||||
Posted in reply to Arcane Jill | 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 Re: Returning a reference to a local variable | ||||
---|---|---|---|---|
| ||||
Posted in reply to Arcane Jill | 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 |
Copyright © 1999-2021 by the D Language Foundation