...
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 | ||||
---|---|---|---|---|
| ||||
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 | ||||
---|---|---|---|---|
| ||||
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 | ||||
---|---|---|---|---|
| ||||
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. | ||||||||
| 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. | |||||||
| LOCRET.* | ||||||||
| 42 D | Fully implemented. | |||||||
PRQA QA-C |
| 3217 | Partially implemented. | ||||||
Splint |
|
...
CERT C++ Secure Coding Standard | DCL30-CPP. Declare objects with appropriate storage durations | ||
ISO/IEC TR 24772:2013 | Dangling References to Stack Frames [DCM] | ||
ISO/IEC TS 17961 (Draft) | Escaping of the address of an automatic object [addrescape] | MISRA-C | Rule 8.6 |
Bibliography
[Coverity 2007] | |
[ISO/IEC 9899:2011] | Section 6.2.4, "Storage Durations of Objects" |
...