Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C w/ Blocks: Stack-based blocks going out of scope

Tags:

People also ask

When a stack variable goes out of scope?

Nothing physical happens. A typical implementation will allocate enough space in the program stack to store all variables at the deepest level of block nesting in the current function. This space is typically allocated in the stack in one shot at the function startup and released back at the function exit.

Is C block a scope?

A Block in C is a set of statements written within the right and left braces. A block may contain more blocks within it, i.e., nested blocks. A variable declared within a Block has a Block Scope. This variable is accessible anywhere within the block and its inner blocks.

What is the block scope variable in C?

Block Scope: A Block is a set of statements enclosed within left and right braces i.e. '{' and '}' respectively. Blocks may be nested in C(a block may contain other blocks inside it). A variable declared inside a block is accessible in the block and all inner blocks of that block, but not accessible outside the block.

What is the use of block in C?

A block statement, or compound statement, lets you group any number of data definitions, declarations, and statements into one statement. All definitions, declarations, and statements enclosed within a single set of braces are treated as a single statement. You can use a block wherever a single statement is allowed.


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 as I may, I cannot come up with a test case that exemplifies this bug. I can create blocks that are instantiated on the stack, but they (seem to) always appear at unique addresses on the stack, even when out of scope with respect to each other.

I imagine that the answer to this is simple, but it escapes me. Can anyone fill the gaps in my (limited) understanding?

EDIT: I've seen this response, but I don't quite understand how that instance can translate to my example posted above. Can someone show me an example using if constructs?