Versions Compared

Key

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

...

In this example, the user defined function calc_size() (not shown) is used to calculate the size of the string other_srting. The result of calc_size() is returned to str_size and used as the size parameter in a call to malloc(). However, if calc_size returned zero, then when the strncpy() is executed, a heap buffer overflow will occur.

Code Block
size_t str_size = calc_size(other_string);
char *str_copy = malloc(str_size);
if (str_copyint main(int argc, char *argv[]) {
  char *str = NULL;

  if (argc != 2) { 
    /* Handle Arguments Error */
  } 
  str = malloc(strlen(argv[1])+1);
  if (str == NULL) {
    /* handleHandle Allocation errorError */
  }	
  strcpy(str_copy, other_string);
argv[1]);

  /* Process str */

  return 0;
}

Compliant Code Example 1

To assure that zero is never passed as a size argument to malloc(), a check must be made on the size parameter.

Code Block


int main(int argc, char *argv[]) {
  char *str = NULL;
  size_t str_size;

  = calc_size(other_string);
if (str_size >if (argc != 2) { 
    /* Handle Arguments Error */
  }
  size = strlen(argv[1])+1;
  if (size == 0) {
    /* Handle charError *str_copy/
  }
  str = malloc(str_size);
  if (str_copy == NULL) {
    /* handleHandle Allocation errorError */
  }	
  strcpy(str_copy, other_string)argv[1]);
  /* Process str */
  return 0;
}

References