Note: This website is archived. For up-to-date information about D projects and development, please visit wiki.dlang.org.

Changes from Version 1 of DontReturnStackDelegateExample

Show
Ignore:
Author:
jcc7 (IP: 68.97.93.38)
Timestamp:
11/12/05 05:05:59 (18 years ago)
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • DontReturnStackDelegateExample

    v0 v1  
     1= Don't Return a Stack Delegate = 
     2 
     3''Part of'' DelegateCategory 
     4 
     5== Description == 
     6 
     7This 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 
     33import std.stdio; 
     34 
     35int 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 
     46int main() {  
     47    foo(); 
     48    return 0; 
     49} 
     50}}} 
     51 
     52== Source == 
     53 
     54Original 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 ||