开发者

Stack block lifespan

int (^b[3])();
for (int i=0; i<3; i++)
    b[i] = ^{ return i;};
for (int i=0; i<3; i++)
    printf("b %d\n", b[i]());

In the first loop a block structure is created, then the address of this structure is assigned to b[i] element and then the block structure is destroyed. Question is why b[i] in second loop contains valid/same pointers to the last state of the block? I would expect the secon开发者_StackOverflow社区d loop to crash because the elements are pointing to invalid stack area.

I know this is not the best piece of code and I'm not using it. But want to understand why after first loop, when the block structure supposed to be destroyed, I have valid stack object.


Your code exhibits undefined behaviour, since you are using a block outside the scope in which it was created. You should write this instead:

b[i] = [^{ return i; } copy];

The variable won't cause a problem because it is actually copied into the block's scope with a const-qualifier added. You can give the block write-access to the variable by declaring the variable with a __block qualifier, which has the odd side-effect of moving the variable (i.e., changing its address) from the stack to the heap when a referencing block is copied.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜