Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Clarified/improved code examples.

...

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
bgColor#FFCCCC
int f(size_t num_elem = /* some initial value */;
n) {
  int error_condition = 0;

  int *x = (int *)malloc(num_elemn * sizeof(int));
  if (x == NULL) {
    return -1;

  /* handle allocation Use x and set error_condition on error. */
}
/* ... */
if (error_condition == 1) {
    /* handleHandle error condition*/
    free(x);
  x}

 = NULL;
}
/* ... */
  free(x);
x  =return NULLerror_condition;
}

Compliant Solution

In this compliant solution, the free a referenced by x is only freed once. This is accomplished by eliminating the call to free() when error_condition is equal to 1set.

Code Block
bgColor#ccccff
int f(size_t num_elem = /* some initial value */;
n) {
  int error_condition = 0;

  if (num_elemn > SIZE_MAX / sizeof(int)) {
    errno  /* Handle overflow */
}
= EOVERFLOW;
    return -1;
  }

  int *x = (int *)malloc(num_elemn * sizeof(int));
  if (x == NULL) {
    /* handleReport allocation error failure to caller. */
    return -1;
  }

  /* ... Use x and set error_condition on error. */

  if (error_condition !== 10) {
    /* Handle error condition and proceed. */
  }

/* ... */
free(x);

x  =return NULLerror_condition;
}

Note that this solution checks for numeric overflow (see INT32-C. Ensure that operations on signed integers do not result in overflow).

...