Versions Compared

Key

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

...

This example demonstrates an error that can occur when memory is freed in different functions. The array, which is referred to by list and its size, number, are then passed to the verify_list() function. If the number of elements in the array is less than the value MIN_SIZE_ALLOWED, list is processed. Otherwise, it is assumed an error has occurred, list is freed, and the function returns. If the error occurs in verify_list(), the dynamic memory referred to by list will be freed twice: once in verify_list() and again at the end of process_list().

Code Block
bgColor#FFcccc

#define MIN_SIZE_ALLOWED 10

int verify_size(char *list, size_t list_size) {
  if (size < MIN_SIZE_ALLOWED) {
    /* Handle Error Condition */
    free(list);
    return -1;
  }

  /* Process list */

  return 0;
}

void process_list(size_t number) {
  char *list = malloc(sizeof(int)number);
  if (list == NULL) {
    /* Handle Allocation Error */
  }

  if (verify_size(list,number) == -1) {
    /* Handle Error */
  }

  /* Continue Processing list */

  free(list);
}

...