1 /* Copyright 2013 Google Inc. All Rights Reserved.
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
7 http://www.apache.org/licenses/LICENSE-2.0
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
16 /* Size-checked memory allocation. */
19 #include "./safe_malloc.h"
21 #if defined(__cplusplus) || defined(c_plusplus)
25 /* Returns 0 in case of overflow of nmemb * size. */
26 static int CheckSizeArgumentsOverflow(uint64_t nmemb
, size_t size
) {
27 const uint64_t total_size
= nmemb
* size
;
28 if (nmemb
== 0) return 1;
29 if ((uint64_t)size
> BROTLI_MAX_ALLOCABLE_MEMORY
/ nmemb
) return 0;
30 if (total_size
!= (size_t)total_size
) return 0;
34 void* BrotliSafeMalloc(uint64_t nmemb
, size_t size
) {
35 if (!CheckSizeArgumentsOverflow(nmemb
, size
)) return NULL
;
36 assert(nmemb
* size
> 0);
37 return malloc((size_t)(nmemb
* size
));
40 #if defined(__cplusplus) || defined(c_plusplus)