...
Code Block | ||||
---|---|---|---|---|
| ||||
const char *p;
void dont_do_this(void) {
const char c_str[] = "This will change";
p = c_str; /* Dangerous */
/* ... */
}
void innocuous(void) {
const char c_str[] = "Surprise, surprise";
}
int main(void) {
dont_do_this();
innocuous(); /* p might be pointing to "Surprise, surprise". */
return 0;
} |
Compliant Solution (Similar Scope)
...
Code Block | ||||
---|---|---|---|---|
| ||||
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. */
|
Alternatively, both p
and c_str
could be declared with static
scope.
...
Code Block | ||||
---|---|---|---|---|
| ||||
void squirrel_away(char **ptr_param) {
char local[10];
/* Initialize array */
*ptr_param = local;
}
void rodent() {
char *ptr;
squirrel_away(&ptr);
/* ptr is live but invalid here. */
}
|
Compliant Solution
The variable local
has static storage duration, 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. */
}
|
Risk Assessment
Referencing an object outside of its lifetime can result in an attacker being able to run arbitrary code.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
DCL30-C | highHigh | probableProbable | highHigh | P6 | L2 |
Automated Detection
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 | |||||||
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 |
|
...