C: Array of automatic storage class?

  • A+
Category:Languages

I'm reading C How to Program and I have a question about storage classes of arrays. In the book it says:

Array and structs are "static" entities in that they remain the same size throughout the program execution (they may, of course, be of automatic storage class and hence created and destroyed each time the blocks in which they're defined are entered and exited)

I'm not sure about what blocks mean, my current understanding is that function/for/while are blocks. I've tried the following:

... for (size_t i=1; i<=2; i++) {     printf("round %c:", i+'0');     int a[10];     show_array(a, 10); // this is a function that prints all elements of `a`.     for (size_t j=0;j<10;j++) {         a[j]=8;     } } 

I got the output:

round 1:0,0,0,0,-1160480784,22023,-1160481168,22023,1594487680,32766, round 2:8,8,8,8,8,8,8,8,8,8, 

It seems like int a[10] is static, and not automatic storage class, am I missing something? (I understand the four storage classes)

I used ideone.com to run my test, if you need this information.

 


You are indeed missing something. a does have automatic storage, and the values that are printed are a consequence of the memory being re-used, not of the storage being persistent. The values will be reset in debug mode (perhaps not by all development environments, but some will set the members to 0xCCCCCCCC on each iteration). Also, good compilers (most compilers, if you enable all warnings) will tell you that you're using uninitialized data here.

If you still don't believe me, try this example. It will show that the memory values in a are overwritten by the values stored in b. The array a ceases to exist at the end of the if statement's dependent block of code, and all of that memory is made available to the system. On the next iteration, it will probably be used for array b, which is why you'll see values of 8 printed in array b, even though they were assigned to a.

for (size_t i=1; i<=2; i++) {     if( i&1 )     {         printf("round %c:", i+'0');         int a[10];         show_array(a, 10);         for (size_t j=0;j<10;j++) a[j]=8;     }     else     {         printf("round %c:", i+'0');         int b[10];         show_array(b, 10);         for (size_t j=0;j<10;j++) b[j]=888;     } } 

For a final confirmation that memory is being re-used, you could modify show_array to print the raw pointer passed in, not just the individual elements. You should see the same address each time.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: