kmalloc: Avoid code duplication.
[dragonfly.git] / contrib / mdocml / compat_reallocarray.c
blobe25d8374bd538ad97e4670e4ffe5a7ae996a75cf
1 #ifdef HAVE_CONFIG_H
2 #include "config.h"
3 #endif
5 #ifdef HAVE_REALLOCARRAY
7 int dummy;
9 #else
11 /* $OpenBSD: malloc.c,v 1.158 2014/04/23 15:07:27 tedu Exp $ */
13 * Copyright (c) 2008 Otto Moerbeek <otto@drijf.net>
15 * Permission to use, copy, modify, and distribute this software for any
16 * purpose with or without fee is hereby granted, provided that the above
17 * copyright notice and this permission notice appear in all copies.
19 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
20 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
21 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
22 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
23 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
24 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
25 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
27 #include <sys/types.h>
28 #include <errno.h>
29 #include <stdint.h>
30 #include <stdlib.h>
32 #define MUL_NO_OVERFLOW (1UL << (sizeof(size_t) * 4))
34 void *
35 reallocarray(void *optr, size_t nmemb, size_t size)
37 if ((nmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&
38 nmemb > 0 && SIZE_MAX / nmemb < size) {
39 errno = ENOMEM;
40 return NULL;
42 return realloc(optr, size * nmemb);
45 #endif /*!HAVE_REALLOCARRAY*/