Versions Compared

Key

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

...

According to the C Standard, section 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.

Attempting to access an object outside of its lifetime can result in undefined behavior and lead to an exploitable vulnerability. (See also undefined behavior 9  of Appendix J in the C Standard.)

Noncompliant Code Example (Static Variables)

...

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

int main(int argc, char *argv[]) {
   char array[10];
   init_array(array);
   /* ... */
   return 0;
}

Noncompliant Code

In this noncompliant code sample, the function squirrel_away() stores a pointer to local stack variable local into a location pointed to by function parameter ptr_param. Since it can be assumed that the pointer variable to which ptr_param points remains alive upon squirrel_away()'s return, it is illegal for local to go out of scope.

...

Tool

Version

Checker

Description

LDRA tool suite

Include Page
LDRA_V
LDRA_V

42 D
71 S

Fully implemented.

Fortify SCA

V. 7.6.0

 

Can detect violations when an array is declared in a function and then a pointer to that array is returned.

Splint
Include Page
Splint_V
Splint_V
  
Compass/ROSE  

Can detect violations of this rule. It automatically detects returning pointers to local variables. Detecting more general cases, such as examples where static pointers are set to local variables which then go out of scope would be difficult.

Coverity

Include Page
Coverity_V
Coverity_V

RETURN_LOCAL

Finds many instances where a function will return a pointer to a local stack variable. Coverity Prevent cannot discover all violations of this rule, so further verification is necessary.

Klocwork

Include Page
Klocwork_V
Klocwork_V

LOCRET.*

 
PRQA QA-C
Include Page
PRQA_V
PRQA_V

3217
3225
3230
4140

Partially implemented.

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

Related Guidelines

...

...

...

ISO/IEC TR 17961(Draft) Escaping of the address of an automatic object [addrescape]
ISO/IEC

...

TR 24772"DCM Dangling references to stack frames"
MISRA-CRule 8.6

Bibliography

[Coverity 2007] 
[ISO/IEC 9899:2011]Section 6.2.4, "Storage Durations of Objects," and section 7.22.3, "Memory Management Functions"

 

 

...