Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

In this 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
size_t number;
int error_condition = 0;

/* initialize number */

int *x = (int *)malloc (number * sizeof(int));
if (x == NULL) {
  /* Handle Allocation Error */
}
/* ... */
if (error_condition == 1) {
  /* Handle Error Condition*/
  free(x);
}
/* ... */
free(x);

...

Only free a pointer to dynamic memory referred to by x once. This is accomplished by removing the call to free() in the section of code executed when error_condition is true.

Code Block
bgColor#ccccff
size_t number;
int error_condition = 0;

/* initialize number */

if (number > SIZE_MAX/sizeof(int)) {
   /* handle overflow */
  }
int *x = (int *)malloc(number * sizeof(int));
if (x == NULL) {
  /* Handle Allocation Error */
}
/* ... */
if (error_condition == 1) {
  /* Handle Error Condition*/
}
/* ... */
free(x);
x = NULL;

...