...
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 | ||
---|---|---|
| ||
const char const *p; void dont_do_this() { const char const str[] = "This will change"; p = str; /* dangerous */ /* ... */ } void innocuous() { const char const str[] = "Surprise, surprise"; } /* ... */ dont_do_this(); innocuous(); /* now, it is likely that p is pointing to "Surprise, surprise" */ |
...
Code Block | ||
---|---|---|
| ||
void this_is_OK() { const char const str[] = "Everything OK"; const char const *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 | ||
---|---|---|
| ||
const char const *p; void is_this_OK() { const char const str[] = "Everything OK?"; p = str; /* ... */ p = NULL; } |
...