...
Noncompliant Code Example
In this noncompliant code example, the memory referred to by x
may be freed twice: once if error_condition
is true and again at the end of the code.
Code Block | ||
---|---|---|
| ||
size_t num_elem = /* some initial value */; int error_condition = 0; int *x = (int *)malloc(num_elem * sizeof(int)); if (x == NULL) { /* Handlehandle Allocationallocation Errorerror */ } /* ... */ if (error_condition == 1) { /* Handlehandle Errorerror Conditioncondition*/ free(x); } /* ... */ free(x); |
Compliant Solution
Only In this compliant solution, the free a pointer to dynamic memory referred to referenced by x
is only freed once. This is accomplished by removing eliminating the call to free()
in the section of code executed when error_condition
is trueequal to 1.
Code Block | ||
---|---|---|
| ||
size_t num_elem = /* some initial value */; int error_condition = 0; if (num_elem > SIZE_MAX/sizeof(int)) { /* handleHandle overflow */ } int *x = (int *)malloc(num_elem * sizeof(int)); if (x == NULL) { /* Handlehandle Allocationallocation Errorerror */ } /* ... */ if (error_condition == 1) { /* Handle Errorerror Conditioncondition*/ } /* ... */ free(x); x = NULL; |
...