github.com/cellofellow/gopkg@v0.0.0-20140722061823-eec0544a62ad/image/webp/libwebp/src/utils/utils.c (about) 1 // Copyright 2012 Google Inc. All Rights Reserved. 2 // 3 // Use of this source code is governed by a BSD-style license 4 // that can be found in the COPYING file in the root of the source 5 // tree. An additional intellectual property rights grant can be found 6 // in the file PATENTS. All contributing project authors may 7 // be found in the AUTHORS file in the root of the source tree. 8 // ----------------------------------------------------------------------------- 9 // 10 // Misc. common utility functions 11 // 12 // Author: Skal (pascal.massimino@gmail.com) 13 14 #include <stdlib.h> 15 #include "./utils.h" 16 17 //------------------------------------------------------------------------------ 18 // Checked memory allocation 19 20 // Returns 0 in case of overflow of nmemb * size. 21 static int CheckSizeArgumentsOverflow(uint64_t nmemb, size_t size) { 22 const uint64_t total_size = nmemb * size; 23 if (nmemb == 0) return 1; 24 if ((uint64_t)size > WEBP_MAX_ALLOCABLE_MEMORY / nmemb) return 0; 25 if (total_size != (size_t)total_size) return 0; 26 return 1; 27 } 28 29 void* WebPSafeMalloc(uint64_t nmemb, size_t size) { 30 if (!CheckSizeArgumentsOverflow(nmemb, size)) return NULL; 31 assert(nmemb * size > 0); 32 return malloc((size_t)(nmemb * size)); 33 } 34 35 void* WebPSafeCalloc(uint64_t nmemb, size_t size) { 36 if (!CheckSizeArgumentsOverflow(nmemb, size)) return NULL; 37 assert(nmemb * size > 0); 38 return calloc((size_t)nmemb, size); 39 } 40 41 //------------------------------------------------------------------------------ 42