Home | History | Annotate | Line # | Download | only in compat
      1  1.1  christos /*	$OpenBSD: reallocarray.c,v 1.1 2014/05/08 21:43:49 deraadt Exp $	*/
      2  1.1  christos /*
      3  1.1  christos  * Copyright (c) 2008 Otto Moerbeek <otto (at) drijf.net>
      4  1.1  christos  *
      5  1.1  christos  * Permission to use, copy, modify, and distribute this software for any
      6  1.1  christos  * purpose with or without fee is hereby granted, provided that the above
      7  1.1  christos  * copyright notice and this permission notice appear in all copies.
      8  1.1  christos  *
      9  1.1  christos  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
     10  1.1  christos  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
     11  1.1  christos  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
     12  1.1  christos  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
     13  1.1  christos  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
     14  1.1  christos  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
     15  1.1  christos  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
     16  1.1  christos  */
     17  1.1  christos 
     18  1.1  christos #include "config.h"
     19  1.1  christos #include <sys/types.h>
     20  1.1  christos #include <errno.h>
     21  1.1  christos #ifdef HAVE_STDINT_H
     22  1.1  christos #include <stdint.h>
     23  1.1  christos #endif
     24  1.1  christos #include <limits.h>
     25  1.1  christos #include <stdlib.h>
     26  1.1  christos 
     27  1.1  christos /*
     28  1.1  christos  * This is sqrt(SIZE_MAX+1), as s1*s2 <= SIZE_MAX
     29  1.1  christos  * if both s1 < MUL_NO_OVERFLOW and s2 < MUL_NO_OVERFLOW
     30  1.1  christos  */
     31  1.1  christos #define MUL_NO_OVERFLOW	((size_t)1 << (sizeof(size_t) * 4))
     32  1.1  christos 
     33  1.1  christos void *
     34  1.1  christos reallocarray(void *optr, size_t nmemb, size_t size)
     35  1.1  christos {
     36  1.1  christos 	if ((nmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&
     37  1.1  christos 	    nmemb > 0 && SIZE_MAX / nmemb < size) {
     38  1.1  christos 		errno = ENOMEM;
     39  1.1  christos 		return NULL;
     40  1.1  christos 	}
     41  1.1  christos 	return realloc(optr, size * nmemb);
     42  1.1  christos }
     43