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. First, an array of integers is dynamically allocated. The array, which is referred to by list and its size, number, are then passed to func2 verify_list(). If the number of elements in the array is greater less than the value MIN_SIZE_ALLOWED, the array list is processed. Otherwise, it is assumed an error has occurred, list is freed, and the function returns. If the error occurs in func2 verify_list(), the dynamic memory referred to by list will be freed twice: once in func2 verify_list() and again at the end of func1 process_list().

Code Block
bgColor#FFcccc
#define MIN_SIZE_ALLOWED 10

voidint func2verify_size(int *list, size_t list_size) {
  if (size < MIN_SIZE_ALLOWED) {
    /* Handle Error Condition */
    free(list);
    return -1;
  }
  /* Process list */
  
  return 0;
}

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

  /* Continue Processing list */

  free(list);
}

...

Code Block
bgColorccccff
#define MIN_SIZE_ALLOWED 10

voidint  func2(int *list, size_t list_size) {
  if (size < MIN_SIZE_ALLOWED) {
     /* Handle Error Condition */
      return;
  }
  /* Process list */
}

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

  /* Continue Processing list */

  free(list);
}

...