...
Attempting to access an object outside of its lifetime can result in an exploitable vulnerability.
...
Noncompliant Code Example (Static Variables)
This non-compliant noncompliant code example declares the variable p
as a pointer to a constant char
with 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 dont_do_this()
function exits.
Code Block | ||
---|---|---|
| ||
const char const *p; void dont_do_this(void) { const char const str[] = "This will change"; p = str; /* dangerous */ /* ... */ } void innocuous(void) { const char const str[] = "Surprise, surprise"; } /* ... */ dont_do_this(); innocuous(); /* p might be pointing to "Surprise, surprise" */ |
...
Code Block | ||
---|---|---|
| ||
void this_is_OK(void) { const char const str[] = "Everything OK"; const char const *p = str; /* ... */ } /* p is inaccessible outside the scope of string str */ |
...
If it is necessary for p
to be defined with file scope, it can be set to NULL
before str
is destroyed. This prevents p
from taking on an indeterminate value, although any references to p
must check for NULL
.
Code Block | ||
---|---|---|
| ||
const char const *p; void is_this_OK(void) { const char const str[] = "Everything OK?"; p = str; /* ... */ p = NULL; } |
...
Noncompliant Code Example (Return Values)
In this example, the function init_array()
incorrectly returns a pointer to a local stack variable.
...
Some compilers generate a warning when a pointer to an automatic variable is returned from a function, as in this example. Compile your code at high warning levels and resolve any warnings (see MSC00-AC. Compile cleanly at high warning levels).
Compliant Solution (Return Values)
...