...
Noncompliant Code Example (Static Variables)
This In this noncompliant code example declares sample, the address of local variable str
is assigned to the variable p
as a pointer to a constant char
with , which has file scope. The value of str
is assigned to p
within the dont_do_this()
function. However, str
has automatic storage duration, so the lifetime of str
ends when the assignment itself is legal, but it is illegal for str
to go out of scope while p
holds its address, as happens at the end of dont_do_this
()
function exits.
Code Block | ||
---|---|---|
| ||
const char *p; void dont_do_this(void) { const char str[] = "This will change"; p = str; /* dangerous */ /* ... */ } void innocuous(void) { const char str[] = "Surprise, surprise"; } /* ... */ dont_do_this(); innocuous(); /* p might be pointing to "Surprise, surprise" */ |
As a result of this undefined behavior, it is likely that p
will refer to the string literal "Surprise, surprise"
after the call to the innocuous()
function.
Compliant Solution (Similar Scope)
...
Noncompliant Code Example (Return Values)
In this examplenoncompliant code sample, the function init_array
()
incorrectly 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; } |
...
Code Block | ||
---|---|---|
| ||
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 an 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.void squirrel_away(char **ptr_param) {
char local10;
/* Initialize array */
*ptr_param = local;
}
void rodent() {
char *ptr;
squirrel_away(&ptr);
/* ptr is live but invalid here */
}
Risk Assessment
Referencing an object outside of its lifetime can result in an attacker being able to run arbitrary code.
...
Tool | Version | Checker | Description | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
|
| ||||||||||||
|
|
|
| ||||||||||||
|
|
|
| ||||||||||||
|
|
|
| ||||||||||||
|
|
|
| ||||||||||||
|
|
|
|
...