Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are exact requirements on automatic storage duration?

Depending on the compiler the following code:

int main()
{
   srand( 0 );
   if( rand() ) {
      char buffer[600 * 1024] = {};
      printf( buffer );
   } else {
      char buffer[500 * 1024] = {};
      printf( buffer );
   }
   return 0;
}

when ran on a system with maximum stack size equal to 1 megabyte either prints an empty string or crashes with a stack overflow.

The difference is because different compilers allocate automatic storage differently. Most compilers allocate storage for all objects on function start, so in the code above they allocate 600+400=1100 kilobytes and that leads to stack overflow. Some compilers are smarter and they see that those two arrays can never be accessible at the same time so they reuse the same memory and only allocate 600 kilobytes and the program runs fine.

Now The Standard says (3.7/1) that storage duration defines the minimum potential lifetime of the storage and then (3.7.2/1) that the storage for these objects [with automatic duration] lasts until the block in which they are created exists.

I don't understand how 3.7/1 and 3.7.2/1 are to be applied together. One says that duration is minimum potential and the other says explicitly that it lasts until the block exists. Looks like according to the first both allocation strategies are legal, but the second demands that only "reuse" allocation strategy is used.

How do 3.7/1 and 3.7.2/1 co-exist? Is it legal to allocate more memory than the program needs in the worst case (the first strategy)?

like image 510
sharptooth Avatar asked Aug 18 '11 06:08

sharptooth


2 Answers

I read 3.7/ as an introductory description and definition of the different storage classe (automatic, static, dynamic) and not as the implementation requirement for each... the implementation requirement for automatich is then described in 3.7.2/1 .

Reading 3.7.2/1 it does not forbid that it exists longer than the block exists (that is just the minimum) - IMHO this is an opening for compiler implementors regarding possible optimizations...

like image 91
Yahia Avatar answered Nov 01 '22 00:11

Yahia


"Lasts until" also is a minimum.

like image 37
MSalters Avatar answered Nov 01 '22 01:11

MSalters