Home | History | Annotate | Download | only in utils
      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 (at) gmail.com)
     13 
     14 #include <stdlib.h>
     15 #include "./utils.h"
     16 
     17 #if defined(__cplusplus) || defined(c_plusplus)
     18 extern "C" {
     19 #endif
     20 
     21 //------------------------------------------------------------------------------
     22 // Checked memory allocation
     23 
     24 // Returns 0 in case of overflow of nmemb * size.
     25 static int CheckSizeArgumentsOverflow(uint64_t nmemb, size_t size) {
     26   const uint64_t total_size = nmemb * size;
     27   if (nmemb == 0) return 1;
     28   if ((uint64_t)size > WEBP_MAX_ALLOCABLE_MEMORY / nmemb) return 0;
     29   if (total_size != (size_t)total_size) return 0;
     30   return 1;
     31 }
     32 
     33 void* WebPSafeMalloc(uint64_t nmemb, size_t size) {
     34   if (!CheckSizeArgumentsOverflow(nmemb, size)) return NULL;
     35   assert(nmemb * size > 0);
     36   return malloc((size_t)(nmemb * size));
     37 }
     38 
     39 void* WebPSafeCalloc(uint64_t nmemb, size_t size) {
     40   if (!CheckSizeArgumentsOverflow(nmemb, size)) return NULL;
     41   assert(nmemb * size > 0);
     42   return calloc((size_t)nmemb, size);
     43 }
     44 
     45 //------------------------------------------------------------------------------
     46 
     47 #if defined(__cplusplus) || defined(c_plusplus)
     48 }    // extern "C"
     49 #endif
     50