Versions Compared

Key

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

...

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

...

Code Block
bgColor#FFCCCC
langc
const char *p;
void dont_do_this(void) {
    const char c_str[] = "This will change";
    p = c_str; /* dangerousDangerous */
    /* ... */
}

void innocuous(void) {
    const char c_str[] = "Surprise, surprise";
}
/* ... */
dont_do_this();
innocuous();
/* p might be pointing to "Surprise, surprise" */

...

Code Block
bgColor#ccccff
langc
void this_is_OK(void) {
    const char c_str[] = "Everything OK";
    const char *p = c_str;
    /* ... */
}
/* p is inaccessible outside the scope of string c_str */

AlternatelyAlternatively, both p and c_str could be declared with static scope.

...

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

...

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

...

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
  

...

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

...