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

...

(p with file scope)

In this compliant solution , the pointer to the constant char p is moved within the this_is_OK() to prevent this variable from being accessed outside of the function p is set to NULL just before str goes out of scope. This prevents p from taking on an indeterminate value.

Code Block
bgColor#ccccff

void is_this_OK() {
    char const str[] = "Everything OK?";
    p = str;
    /* ... */
    p = NULL;
}

Compliant Solution (p with block scope)

Alternatively, this example can be corrected by declaring p with the same scope as str. This approach also prevents p from taking on an indeterminate value.

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

...