...
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 | ||
---|---|---|
| ||
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 | ||
---|---|---|
| ||
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 | ||
---|---|---|
| ||
char const char *p; void is_this_OK() { char const char str[] = "Everything OK?"; p = str; /* ... */ p = NULL; } |
...