Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Every object has a storage duration that determines its lifetime. There are four storage durations: static, threadautomatic, and or allocated.

According to the C Standard, subclause 6.2.4, paragraph 2 [ISO/IEC 9899:2011],

The lifetime of an object is the portion of program execution during which storage is guaranteed to be reserved for it. An object exists, has a constant address, and retains its last-stored value throughout its lifetime. If an object is referred to outside of its lifetime, the behavior is undefined. The value of a pointer becomes indeterminate when the object it points to reaches the end of its lifetime.

Do not attempt to assess access an object outside of its lifetime.   Attempting to do so is undefined behavior and can lead to an exploitable vulnerability. (See see also undefined behavior 9 in Appendix J of the C Standard, Annex J).)

Noncompliant Code Example (Differing Storage Durations)

In this noncompliant code example, the address of a the variable c_str with automatic storage duration is assigned to the variable p, which has static storage duration. The assignment itself is valid, but it is invalid for c_str to go out of scope while p holds its address, as happens at the end of dont_do_this().

...

In this noncompliant code sample, the function init_array() returns a pointer to a character array with automatic storage duration, which could be accessed by is accessible to the caller:

Code Block
bgColor#FFCCCC
langc
char *init_array(void) {
  char array[10];
  /* Initialize array */
  return array;
}

Some compilers generate a diagnostic message when a pointer to an object with automatic storage duration is returned from a function, as in this example. Compile your code at high warning levels and resolve any diagnostic messages . (See see MSC00-C. Compile cleanly at high warning levels).)

Compliant Solution (Return Values)

The solution, in this case, depends on the intent of the programmer. If the intent is to modify the value of array and have that modification persist outside of the scope of init_array(), the desired behavior can be achieved by declaring array elsewhere and passing it as an argument to init_array():

...

In this noncompliant code example, the function squirrel_away() stores a pointer to local stack variable local into a location pointed to by function parameter ptr_param. Upon the return of squirrel_away(), the pointer ptr_param points to a variable that has an expired lifetime.

...

In this compliant solution, the variable local has static storage duration; consequently, ptr can be used to reference the local array within the rodent() function:

...

[Coverity 2007] 
[ISO/IEC 9899:2011]Subclause 6.2.4, "Storage Durations of Objects"

...

...