Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Edited by sciSpider (sch jbop) (X_X)@==(Q_Q)@

...

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 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
bgColor#FFCCCC
char const char *p;
void dont_do_this() {
    char const char str[] = "This will change";
    p = str; /* dangerous */
    /* ... */
}

void innocuous() {
    char const char str[] = "Surprise, surprise";
}
/* ... */
dont_do_this();
innocuous();
/* now, it is likely that p is pointing to "Surprise, surprise" */

...

Code Block
bgColor#ccccff
void this_is_OK() {
    char const char str[] = "Everything OK";
    char const char *p = str;
    /* ... */
}
/* pointer p is now 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
bgColor#ccccff
char const char *p;
void is_this_OK() {
    char const char str[] = "Everything OK?";
    p = str;
    /* ... */
    p = NULL;
}

...