Versions Compared

Key

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

...

Code Block
bgColor#ffcccc
int create_table(size_t size) {
  char **table;
  size_t table_size = malloc(size * sizeof(char *));;
  /* Check for integer overflow on multiplication */

  malloc(table_size)
  if(table == NULL) {
    /* Handle error condition */
  }
  /* ... */
  return 0;
}

Wiki MarkupHowever, since {{size}} can be controlled by the user, it could be specified to be either large enough to consume large amounts of system resources and still succeed or large enough to cause the call to {{malloc()}} to fail, which, depending on how error handling is implemented, may result in a denial of service condition (note that this function also violates \[[MEM06-A. Do not use user-defined functions as parameters to allocation routines]\]).

Compliant Solution

This compliant solution defines an acceptable range for table size as 1 to MAX_TABLE_SIZE. Note that the size parameter is typed as size_t and is by definition unsigned, thus, it need not be checked that it is negative (see INT01-A. Use size_t for all integer values representing the size of an object).

Code Block
bgColor#ccccff
enum { MAX_TABLE_SIZE = 256 };

int create_table(size_t size) {
  char **table;
  size_t table_size = size * sizeof(char *);
  /* Check for integer overflow on multiplication */

  if(size == 0 || size > MAX_TABLE_SIZE) {
    /* Handle invalid size */
  }

  table = malloc(size * sizeof(char *)table_size);
  if(table == NULL) {
    /* Handle error condition */
  }
  /* ... */
  return 0;
}

...