...
In this code example, the second operand of the logical OR operator invokes a function that results in side effects.
Code Block | ||||
---|---|---|---|---|
| ||||
char *p = /* initialize, may or may not be NULL */ if (p || (p = (char *) malloc(BUF_SIZE)) ) { /* do stuff with p */ free(p); p = NULL; } else { /* handle malloc() error */ return; } |
...
In this compliant solution, a second pointer, q
, is used to indicate whether malloc()
is called; if not, q
remains set to NULL. Passing NULL to free()
is guaranteed to safely do nothing.
Code Block | ||||
---|---|---|---|---|
| ||||
char *p; char *q = NULL; if (p == NULL) { q = (char *) malloc(BUF_SIZE); p = q; } if (p == NULL) { /* handle malloc() error */ return; } /* do stuff with p */ free(q); q = NULL; |
...