I came across this code on dispatch_block_t from the Grand Central Dispatch Resource page and I do not quite understand if its wrong or right and why is it wrong or right.
Source:
https://developer.apple.com/library/ios/documentation/Performance/Reference/GCD_libdispatch_Ref/
Code:
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;
}
It says that:
As the example demonstrates, the address of a stack variable is escaping the scope in which it is allocated.
I am having a hard time to understand why calling the dispatch_block
(via block()
) is unsafe?
Can anyone help?