utils.c revision 1e7bf8805bd030c19924a5306837ecd72c295751
1// Copyright 2012 Google Inc. All Rights Reserved. 2// 3// This code is licensed under the same terms as WebM: 4// Software License Agreement: http://www.webmproject.org/license/software/ 5// Additional IP Rights Grant: http://www.webmproject.org/license/additional/ 6// ----------------------------------------------------------------------------- 7// 8// Misc. common utility functions 9// 10// Author: Skal (pascal.massimino@gmail.com) 11 12#include <stdlib.h> 13#include "./utils.h" 14 15#if defined(__cplusplus) || defined(c_plusplus) 16extern "C" { 17#endif 18 19//------------------------------------------------------------------------------ 20// Checked memory allocation 21 22// Returns 0 in case of overflow of nmemb * size. 23static int CheckSizeArgumentsOverflow(uint64_t nmemb, size_t size) { 24 const uint64_t total_size = nmemb * size; 25 if (nmemb == 0) return 1; 26 if ((uint64_t)size > WEBP_MAX_ALLOCABLE_MEMORY / nmemb) return 0; 27 if (total_size != (size_t)total_size) return 0; 28 return 1; 29} 30 31void* WebPSafeMalloc(uint64_t nmemb, size_t size) { 32 if (!CheckSizeArgumentsOverflow(nmemb, size)) return NULL; 33 assert(nmemb * size > 0); 34 return malloc((size_t)(nmemb * size)); 35} 36 37void* WebPSafeCalloc(uint64_t nmemb, size_t size) { 38 if (!CheckSizeArgumentsOverflow(nmemb, size)) return NULL; 39 assert(nmemb * size > 0); 40 return calloc((size_t)nmemb, size); 41} 42 43//------------------------------------------------------------------------------ 44 45#if defined(__cplusplus) || defined(c_plusplus) 46} // extern "C" 47#endif 48