1

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?

nburk
  • 22,409
  • 18
  • 87
  • 132
Vasko
  • 23
  • 3
  • I believe this [answer](http://stackoverflow.com/a/13888303/299924) covers the situation. – trojanfoe Mar 29 '16 at 16:40
  • Yes, it is a dupe. To clarify: When a block is declared, it starts out life on the stack (most of the time). So, when you declare a block in the `{...}` of an `if` statement, it is only valid in the scope of that `if` statement. If you use it outside the scope-- `block();` after the `if { ...}`, the behavior is undefined because the block was defined in a scope that no longer exists. – bbum Mar 29 '16 at 17:10
  • Clearly "block" is the address of an item that is out of scope. That means it is the address of something that doesn't even exist anymore. How on earth could you imagine that using the address of an item that doesn't even exist anymore could be safe? – gnasher729 Mar 29 '16 at 19:18
  • @bbum But "block" is defined(i.e. dispatch_block_t block;) in the same scope where it is called. It may be declared/assigned in the if statement but there should not be any compilation errors when you `block()`. And if I am wrong does this also relate to primitive types? If for example i define `int y` and assign `y` inside the if conditions, is that wrong? – Vasko Mar 29 '16 at 19:59
  • @Vasko the definition of the variable is in the outer scope. The definition of the actual block, which starts life on the stack, is in that inner scope. – bbum Mar 30 '16 at 23:34
  • @bbum Oh ok. I got it. Thank you. – Vasko Mar 31 '16 at 14:51

0 Answers0