Storage Duration

Storage duration -
Storage duration is the manner in which an object has memory allocated for it.

Storage duration applies to objects.

Scope and storage duration are separate issues.

Storage Durations in C++ - Briefly

1. Automatic storage duration Automatic storage duration objects exist only at certain points during execution.
2. Static storage duration Static storage duration objects have entire program life duration.
3. Dynamic storage duration Dynamic storage duration objects have a lifetime determined by the programmer.

Storage Durations in C++

1. Automatic storage
duration
  • Automatic storage duration objects exist only at certain points during execution.
  • Automatic storage duration objects are created and initialized (if an intializer is present) every time the block they are declared in is entered, they exist only while the block is active (its statements are being executed), and are destroyed when the block is exited. Their value is lost when they are destroyed.
  • For built-in types, if uninitialized these objects have an undefined value.
  • Local/block scope objects and function parameters have automatic sotrage duration by default.
2. Static storage
duration
  • Static storage duration objects have entire program life duration.
  • For static storage duration objects storage is allocated and initialized only once prior to execution of the first statement for these objects and they have entire program length duration. Their value is maintained for the program duration. This doesn't mean that these objects may be used anywhere, at any time, scope is a separate issue.
  • Global scope objects have static storage duration.
3. Dynamic storage
duration
  • Dynamic storage duration objects have a lifetime determined by the programmer.
  • Dynamic storage duration objects are created by the programer with the new keyword and exist until they are destroyed by the programmer with the delete keyword.
  • It is the programmer's responsibility to delete a dynamic storage duration object when it is no longer needed. Failure to do so results in memory leaks whereby memory consumed is not released and the supply eventually runs out.

slides