Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Deleted MISRA 2004 rule 8.6 (which is deleted from 2012)

...

If it is necessary for p to be defined with file scope, but str with a more limited scope, then p can be set to NULL before str is destroyed. This practice prevents p from taking on an indeterminate value, although any references to p must check for NULL.

...

In this noncompliant code sample, the function init_array() returns a pointer to a local stack variable, which could be accessed by the caller.:

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

...

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().:

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;
}

...

The variable local does not go out of scope for the entire program so, ptr is live and valid in the function rodent().:

Code Block
bgColor#ccccff
langc
char local[10];
 
void squirrel_away(char **ptr_param) {
    /* Initialize array */
   *ptr_param = local;
}

void rodent() {
  char *ptr;
  squirrel_away(&ptr);
  /* ptr is live and valid here */
}

...

Tool

Version

Checker

Description

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.

Fortify SCA

7.6.0

 

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

Klocwork

Include Page
Klocwork_V
Klocwork_V

LOCRET.*

 

LDRA tool suite

Include Page
LDRA_V
LDRA_V

42 D
71 S

Fully implemented.
PRQA QA-C
Include Page
PRQA_V
PRQA_V

3217
3225
3230
4140

Partially implemented.
Splint
Include Page
Splint_V
Splint_V
  

...

CERT C++ Secure Coding StandardDCL30-CPP. Declare objects with appropriate storage durations
ISO/IEC TR 24772:2013Dangling References to Stack Frames [DCM]
ISO/IEC TS 17961 (Draft)Escaping of the address of an automatic object [addrescape]MISRA-CRule 8.6

Bibliography

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

...