Path: blob/main/contrib/libdiff/compat/recallocarray.c
35065 views
/* $OpenBSD: recallocarray.c,v 1.1 2017/03/06 18:44:21 otto Exp $ */1/*2* Copyright (c) 2008, 2017 Otto Moerbeek <[email protected]>3*4* Permission to use, copy, modify, and distribute this software for any5* purpose with or without fee is hereby granted, provided that the above6* copyright notice and this permission notice appear in all copies.7*8* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES9* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF10* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR11* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES12* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN13* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF14* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.15*/1617#include <errno.h>18#include <stdlib.h>19#include <stdint.h>20#include <string.h>21#include <unistd.h>2223/*24* This is sqrt(SIZE_MAX+1), as s1*s2 <= SIZE_MAX25* if both s1 < MUL_NO_OVERFLOW and s2 < MUL_NO_OVERFLOW26*/27#define MUL_NO_OVERFLOW ((size_t)1 << (sizeof(size_t) * 4))2829void *30recallocarray(void *ptr, size_t oldnmemb, size_t newnmemb, size_t size)31{32size_t oldsize, newsize;33void *newptr;3435if (ptr == NULL)36return calloc(newnmemb, size);3738if ((newnmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&39newnmemb > 0 && SIZE_MAX / newnmemb < size) {40errno = ENOMEM;41return NULL;42}43newsize = newnmemb * size;4445if ((oldnmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&46oldnmemb > 0 && SIZE_MAX / oldnmemb < size) {47errno = EINVAL;48return NULL;49}50oldsize = oldnmemb * size;5152/*53* Don't bother too much if we're shrinking just a bit,54* we do not shrink for series of small steps, oh well.55*/56if (newsize <= oldsize) {57size_t d = oldsize - newsize;5859if (d < oldsize / 2 && d < getpagesize()) {60memset((char *)ptr + newsize, 0, d);61return ptr;62}63}6465newptr = malloc(newsize);66if (newptr == NULL)67return NULL;6869if (newsize > oldsize) {70memcpy(newptr, ptr, oldsize);71memset((char *)newptr + oldsize, 0, newsize - oldsize);72} else73memcpy(newptr, ptr, newsize);7475explicit_bzero(ptr, oldsize);76free(ptr);7778return newptr;79}808182