1 /* $NetBSD: reallocarr.c,v 1.2 2015/07/16 00:03:59 kamil Exp $ */ 2 3 /*- 4 * Copyright (c) 2015 Joerg Sonnenberger <joerg@NetBSD.org>. 5 * All rights reserved. 6 * 7 * Redistribution and use in source and binary forms, with or without 8 * modification, are permitted provided that the following conditions 9 * are met: 10 * 11 * 1. Redistributions of source code must retain the above copyright 12 * notice, this list of conditions and the following disclaimer. 13 * 2. Redistributions in binary form must reproduce the above copyright 14 * notice, this list of conditions and the following disclaimer in 15 * the documentation and/or other materials provided with the 16 * distribution. 17 * 18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 21 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 22 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 23 * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING, 24 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 25 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 26 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 27 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT 28 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 29 * SUCH DAMAGE. 30 */ 31 32 #include <sys/cdefs.h> 33 __RCSID("$NetBSD: reallocarr.c,v 1.2 2015/07/16 00:03:59 kamil Exp $"); 34 35 #include "namespace.h" 36 #include <errno.h> 37 /* Old POSIX has SIZE_MAX in limits.h */ 38 #include <limits.h> 39 #include <stdint.h> 40 #include <stdlib.h> 41 #include <string.h> 42 43 __CTASSERT(65535 < SIZE_MAX / 65535); 44 45 #ifdef _LIBC 46 #ifdef __weak_alias 47 __weak_alias(reallocarr, _reallocarr) 48 #endif 49 #endif 50 51 int 52 reallocarr(void *ptr, size_t num, size_t size) 53 { 54 int saved_errno, result; 55 void *optr; 56 void *nptr; 57 58 saved_errno = errno; 59 memcpy(&optr, ptr, sizeof(ptr)); 60 if (num == 0 || size == 0) { 61 free(optr); 62 nptr = NULL; 63 memcpy(ptr, &nptr, sizeof(ptr)); 64 errno = saved_errno; 65 return 0; 66 } 67 if ((num >= 65535 || size >= 65535) && num > SIZE_MAX / size) 68 return EOVERFLOW; 69 nptr = realloc(optr, num * size); 70 if (nptr == NULL) { 71 result = errno; 72 } else { 73 result = 0; 74 memcpy(ptr, &nptr, sizeof(ptr)); 75 } 76 errno = saved_errno; 77 return result; 78 } 79