| 1 | = Don't Return a Stack Delegate = |
---|
| 2 | |
---|
| 3 | ''Part of'' DelegateCategory |
---|
| 4 | |
---|
| 5 | == Description == |
---|
| 6 | |
---|
| 7 | This shows code that is '''broken''', namely returning a stack delegate from a function. |
---|
| 8 | |
---|
| 9 | == Example == |
---|
| 10 | |
---|
| 11 | {{{ |
---|
| 12 | #!d |
---|
| 13 | |
---|
| 14 | /* NOTE NOTE NOTE |
---|
| 15 | * |
---|
| 16 | * THIS CODE IS BROKEN. This is an example of something that you |
---|
| 17 | * should NOT do! |
---|
| 18 | * |
---|
| 19 | * You can never return a stack delegate because the data pointer of that |
---|
| 20 | * delegate points to the stack frame where the delegate was created. Once |
---|
| 21 | * you return from the function, that stack frame goes away and the memory |
---|
| 22 | * is reused by some other function. |
---|
| 23 | * |
---|
| 24 | * Most likely, when you call this stack delegate, your program won't crash |
---|
| 25 | * (since the pointer points to a valid address in the stack), but you will be |
---|
| 26 | * reading trash values, since the memory has been reused by some other |
---|
| 27 | * function. |
---|
| 28 | * |
---|
| 29 | * Of course, if one of the variables is a pointer, then you would crash when |
---|
| 30 | * you read & follow the pointer that is no longer valid. |
---|
| 31 | */ |
---|
| 32 | |
---|
| 33 | import std.stdio; |
---|
| 34 | |
---|
| 35 | int delegate() foo() { |
---|
| 36 | int a = 1; |
---|
| 37 | int b = 2; |
---|
| 38 | |
---|
| 39 | writefln("int delegate() foo() is called. Locals a = %d, b = %d", a, b); |
---|
| 40 | writefln("BUG! You must NEVER return a stack delegate!"); |
---|
| 41 | |
---|
| 42 | return delegate int() { return a+b; }; |
---|
| 43 | } |
---|
| 44 | |
---|
| 45 | |
---|
| 46 | int main() { |
---|
| 47 | foo(); |
---|
| 48 | return 0; |
---|
| 49 | } |
---|
| 50 | }}} |
---|
| 51 | |
---|
| 52 | == Source == |
---|
| 53 | |
---|
| 54 | Original contribution by Russ Lewis. Changed based on suggestions by Blandger. |
---|
| 55 | |
---|
| 56 | || Link || http://www.dsource.org/tutorials/index.php?show_example=109 || |
---|
| 57 | || Edited by || jcc7 || |
---|
| 58 | || Date/Time || Thu Jul 29, 2004 9:42 pm || |