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

Don't Return a Stack Delegate

Part of DelegateCategory


This shows code that is broken, namely returning a stack delegate from a function.


 * THIS CODE IS BROKEN.  This is an example of something that you
 * should NOT do!
 * You can never return a stack delegate because the data pointer of that
 * delegate points to the stack frame where the delegate was created.  Once
 * you return from the function, that stack frame goes away and the memory
 * is reused by some other function.
 * Most likely, when you call this stack delegate, your program won't crash
 * (since the pointer points to a valid address in the stack), but you will be
 * reading trash values, since the memory has been reused by some other
 * function.
 * Of course, if one of the variables is a pointer, then you would crash when
 * you read & follow the pointer that is no longer valid.

import std.stdio;

int delegate() foo() {
    int a = 1;
    int b = 2;

    writefln("int delegate() foo() is called. Locals a = %d, b = %d", a, b);
    writefln("BUG!  You must NEVER return a stack delegate!");

    return delegate int() { return a+b; };

int main() { 
    return 0;


Original contribution by Russ Lewis. Changed based on suggestions by Blandger.

Edited by jcc7
Date/Time Thu Jul 29, 2004 9:42 pm