...
In this noncompliant code sampleexample, the address of local variable c_str
is assigned to the variable p
, which has static storage duration. The assignment itself is valid, but it is invalid for c_str
to go out of scope while p
holds its address, as happens at the end of dont_do_this
()
.
Code Block | ||||
---|---|---|---|---|
| ||||
#include <stdio.h> 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"printf("%s\n", p); } int main(void) { dont_do_this(); innocuous(); /* p might be pointing to "Surprise, surprise" */ return 0; } |
Compliant Solution (Similar Scope)
...
Some compilers generate a warning diagnostic message 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 warningsdiagnostic messages. (See MSC00-C. Compile cleanly at high warning levels.)
...
Code Block | ||||
---|---|---|---|---|
| ||||
#include <stddef.h> void init_array(char array[]*array, size_t len) { /* Initialize array */ return; } int main(int argc, char *argv[]) { char array[10]; init_array(array, sizeof(array) / sizeof(array[0])); /* ... */ return 0; } |
Noncompliant Code Example (Output Parameter)
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
. Upon the return of squirrel_away()
the pointer ptr_param
points to a variable that has an expired lifetime.
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 (Output Parameter)
The variable local
has static storage duration, so ptr
is live and valid in the function rodent()
:
...
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
CERT C Secure Coding Standard | MSC00-C. Compile cleanly at high warning levels |
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 | Escaping of the address of an automatic object [addrescape] |
...
[Coverity 2007] | |
[ISO/IEC 9899:2011] | Subclause 6.2.4, "Storage Durations of Objects" |
...