Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

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)

In this compliant solution, p is declared with the same scope as str, preventing p from taking on an indeterminate value outside of this_is_OK().

Code Block
bgColor#ccccff
void this_is_OK(void) {
    const char str[] = "Everything OK";
    const char *p = str;
    /* ... */
}
/* p is inaccessible outside the scope of string str */

Alternately, both p and str could be declared with static scope.

Compliant Solution (

...

Differing Scope)

If it is necessary for p to be defined with file scope, but str with a more limited scope, it then p 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.

...