Overview
The memory that is allocated at the time of compilation of a program is called as static memory. The compiler allocates the memory for all the variables, arrays, and objects created by the programmer, hence the memory allocation is by default static in C++. One of the major limitations of the static memory allocation is that, the amount of memory required by the program must be exactly known at the time of compilation, to avoid over allocation or under allocation of the required space. However, in many cases the programmer might not know the exact amount of memory to be allocated for implementing the functionality. Hence, in the case of static memory allocation the programmer might overestimate the actual amount of memory required by the program at run time. Therefore, the programmer may end up allocating the memory which is much higher than the actual amount of memory required when the program runs. This will result into large wastage of storage space in the primary memory of the computer system. On the other hand, it is also possible that the programmer underestimates the amount of memory required by the program at run time, then the program may crash at run time because of lack of storage space allocated by the programmer in the primary memory, thereby resulting into an ‘out of memory’ error.
As an example to understand static memory allocation, let us create an array of size 3 by using the following statement:
float a[3];
As each floating point element requires 4 bytes in memory, compiler will allocate the memory for array a as 4 × 3 = 12 bytes. Recall that, we cannot create an array by indirectly specifying the size of array in terms of another variable. For instance, let us create a variable n initialized to a value 3 and then create an array a with the size of array specified in terms of n as follows:
int n=3;
float a[n]; /*ERROR: value of n is not known at the time of compilation*/
Logically, the statements float a[3]; and float a[n]; will have a same meaning because the value of variable n is initialized as 3.
Review the options below to login to check your access.
Log in with your Cambridge Aspire website account to check access.
If you believe you should have access to this content, please contact your institutional librarian or consult our FAQ page for further information about accessing our content.