Trantorian Gazette

Initialization of automatic variables in C

Wednesday Aug 29, 2007

I recently participated in a code inspection for my colleague, Prakash. He was fixing a bug caused by a jump into a block of code that resulted in an automatic variable failing to be initialized. Let me show you:


     goto fragmented;

  [deleted]

     if (u1) {
          [deleted]
          boolean_t     pruned=B_FALSE;
fragmented:
          [deleted]
          if (pruned && offset != 0) {

So, in the above code the variable "pruned" is not being initialized. It seemed to me that it would either be illegal to jump in like this at all, or that it would "just work" and that the initialization would be done. Prakash thought so too but was able to fix the problem pragmatically by adding the line "pruned = B_FALSE;" just after the label.

I was curious, so I went to the ISO C standard and looked it up. The language used is a bit vague, but apparently storage for automatic variables must be allocated upon entry to a block by any means (meaning that the goto is legal) but that initialization of that storage only occurs when the execution passed over the lines of code that declare the variable. This guarantees that the variables are initialized in a deterministic order, but in this case it means that pruned isn't initialized at all, since execution jumps to just after it is declared.

I know you probably already knew this, but it was news to Prakash and me. Well, live and learn.

Like this post? del.icio.us | furl | slashdot | technorati | digg
Comments:

Post a Comment:
Comments are closed for this entry.