...
This non-compliant 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 dontDoThisdont_do_this() function. However, str has automatic storage duration so the lifetime of str ends when the dontDoThisdont_do_this() function exits.
| Code Block | ||
|---|---|---|
| ||
char const char *p; void dontDoThisdont_do_this() { char const char *str[20] = "This will change"; p = str; //* dangerous */ /* ... */ } void innocuous() { char const char *str[20] = "Surprise, surprise"; } /* ... dontDoThis */ dont_do_this(); innocuous(); //* now, it is likely that p is 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.
...
In this compliant solution, the pointer to the constant char p is moved within the thisIsOKthis_is_OK() to prevent this variable from being accessed outside of the function.
| Code Block | ||
|---|---|---|
| ||
void thisIsOKthis_is_OK() { char const char *str[20] = "Everything OK"; char const char *p = str; /* ... */ } //* pointer p is now inaccessible outside the scope of string str */ |
Risk Assessment
Referencing an object outside of its lifetime could result in an attacker being able to run arbitrary code.
...