...
Code Block | ||||
---|---|---|---|---|
| ||||
const char *p; void dont_do_this(void) { const char c_str[] = "This will change"; p = c_str; /* Dangerous */ /* ... */ } void innocuous(void) { const char c_str[] = "Surprise, surprise"; } /* ... */ int main(void) { dont_do_this(); innocuous(); /* p might be pointing to "Surprise, surprise" */ return 0; } |
Compliant Solution (Similar Scope)
...
In this noncompliant code sample, the function squirrel_away()
stores a pointer to local stack variable local
into a location pointed to by function parameter ptr_param
. Because it can be assumed that the pointer variable to which ptr_param
points remains alive upon Upon the return of squirrel_away()
's return, it is invalid for local
to go out of scope the pointer ptr_param
points to a variable that has an expired lifetime.
Code Block | ||||
---|---|---|---|---|
| ||||
void squirrel_away(char **ptr_param) { char local[10]; /* Initialize array */ *ptr_param = local; } void rodent() { char *ptr; squirrel_away(&ptr); /* ptr is live but invalid here */ } |
...