Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens to statically allocated memory after its scope ends?

void PrintArray()
{
  int a[4] = {4,3,1,5};
  for(int i=0; i<4; i++)
    cout<<a[i];
}

What Exactly happens to the memory allocated to the pointer variable 'a' and the 4-integer block pointed to by 'a' after this function's call is completed? Does the memory of the block and pointer variable get de-allocated or does it create some sort of memory leak?

like image 701
Jobin Jose Avatar asked Jan 26 '26 23:01

Jobin Jose


1 Answers

a is not a static variable it is an automatic variable, from the draft C99 standard section 6.2.4 Storage durations of objects paragraph 4 says:

An object whose identifier is declared with no linkage and without the storage-class specifier static has automatic storage duration.

In paragraphs 3 it describes the lifetime of static as the lifetime of the program and in paragraph 5 says:

For such an object that does not have a variable length array type, its lifetime extends from entry into the block with which it is associated until execution of that block ends in any way. [...]

So in other words for an automatic variable it's lifetime extends to it's scope, in this case as scope is the function PrintArray and the storage associated with it is released after that scope is exited.

For C++ the relevant section from the draft standard is 3.7.3 Automatic storage duration paragraph 1 says:

Block-scope variables explicitly declared register or not explicitly declared static or extern have automatic storage duration. The storage for these entities lasts until the block in which they are created exits.

like image 183
Shafik Yaghmour Avatar answered Jan 29 '26 13:01

Shafik Yaghmour



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!