In one of Apple's header files for libdispatch , queue.h , the following warning appears:
// The declaration of a block allocates storage on the stack. // Therefore, this is an invalid construct: dispatch_block_t block; if (x) { block = ^{ printf("true\n"); }; } else { block = ^{ printf("false\n"); }; } block(); // unsafe!!! // What is happening behind the scenes: if (x) { struct Block __tmp_1 = ...; // setup details block = &__tmp_1; } else { struct Block __tmp_2 = ...; // setup details block = &__tmp_2; } // As the example demonstrates, the address of a stack variable is // escaping the scope in which it is allocated. That is a classic C bug.
Try it as I can, I canβt come up with a test case illustrating this error. I can create blocks that are created on the stack, but they (seem to) always appear at unique addresses on the stack, even if they are inaccessible to each other.
I guess the answer to this question is simple, but it eludes me. Can someone fill in the blanks in my (limited) understanding?
EDIT : I saw this answer, but I donβt quite understand how this instance can translate to my example published above. Can someone show me an example using if constructs?
c objective-c-blocks grand-central-dispatch
Sedate alien
source share