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