1 // Copyright 2012 Google Inc. All Rights Reserved.
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 // -----------------------------------------------------------------------------
10 // Misc. common utility functions
12 // Author: Skal (pascal.massimino@gmail.com)
17 //------------------------------------------------------------------------------
18 // Checked memory allocation
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;
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
));
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
);
41 //------------------------------------------------------------------------------