Print this page
4922 all calloc() implementations should check for overflow

Split Close
Expand all
Collapse all
          --- old/usr/src/lib/libmalloc/common/malloc.c
          +++ new/usr/src/lib/libmalloc/common/malloc.c
↓ open down ↓ 19 lines elided ↑ open up ↑
  20   20   */
  21   21  
  22   22  /*
  23   23   * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
  24   24   * Use is subject to license terms.
  25   25   */
  26   26  
  27   27  /*      Copyright (c) 1988 AT&T */
  28   28  /*        All Rights Reserved   */
  29   29  
  30      -#pragma ident   "%Z%%M% %I%     %E% SMI"
  31      -
  32   30  #include <sys/types.h>
  33   31  
  34   32  #ifndef debug
  35   33  #define NDEBUG
  36   34  #endif
  37   35  
  38   36  #include <stdlib.h>
  39   37  #include <string.h>
       38 +#include <errno.h>
  40   39  #include "assert.h"
  41   40  #include "malloc.h"
  42   41  #include "mallint.h"
  43   42  #include <thread.h>
  44   43  #include <pthread.h>
  45   44  #include <synch.h>
  46   45  #include <unistd.h>
  47   46  #include <limits.h>
  48   47  
  49   48  static mutex_t mlock = DEFAULTMUTEX;
↓ open down ↓ 788 lines elided ↑ open up ↑
 838  837  
 839  838  
 840  839  /*
 841  840   * calloc - allocate and clear memory block
 842  841   */
 843  842  
 844  843  void *
 845  844  calloc(size_t num, size_t size)
 846  845  {
 847  846          char *mp;
      847 +        size_t total;
      848 +
      849 +        if (num == 0 || size == 0) {
      850 +                total = 0;
      851 +        } else {
      852 +                total = num * size;
      853 +
      854 +                /* check for overflow */
      855 +                if ((total / num) != size) {
      856 +                        errno = ENOMEM;
      857 +                        return (NULL);
      858 +                }
      859 +        }
 848  860  
 849      -        num *= size;
 850      -        mp = malloc(num);
      861 +        mp = malloc(total);
 851  862          if (mp == NULL)
 852  863                  return (NULL);
 853      -        (void) memset(mp, 0, num);
      864 +        (void) memset(mp, 0, total);
 854  865          return (mp);
 855  866  }
 856  867  
 857  868  
 858  869  /*
 859  870   * Mallopt - set options for allocation
 860  871   *
 861  872   *      Mallopt provides for control over the allocation algorithm.
 862  873   *      The cmds available are:
 863  874   *
↓ open down ↓ 328 lines elided ↑ open up ↑
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX