OmniSciDB  72c90bc290
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
checked_alloc.h
Go to the documentation of this file.
1 /*
2  * Copyright 2022 HEAVY.AI, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef CHECKED_ALLOC_H
18 #define CHECKED_ALLOC_H
19 
20 #define BOOST_STACKTRACE_GNU_SOURCE_NOT_REQUIRED 1
21 
23 
24 #include <cstdlib>
25 #include <ostream>
26 #include <stdexcept>
27 #include <string>
28 #include "../Logger/Logger.h"
29 #include "../Shared/types.h"
30 
31 class OutOfHostMemory : public std::bad_alloc {
32  public:
33  OutOfHostMemory(const size_t size)
34  : what_str_("Not enough CPU memory available to allocate " + std::to_string(size)) {
35  VLOG(1) << "Failed to allocate " << size << " bytes\n"
36  << boost::stacktrace::stacktrace();
37  }
38 
39  const char* what() const noexcept final { return what_str_.c_str(); }
40 
41  private:
42  const std::string what_str_;
43 };
44 
45 inline void* checked_malloc(const size_t size) {
46  auto ptr = malloc(size);
47  if (!ptr) {
48  throw OutOfHostMemory(size);
49  }
50  return ptr;
51 }
52 
53 inline void* checked_calloc(const size_t nmemb, const size_t size) {
54  auto ptr = calloc(nmemb, size);
55  if (!ptr) {
56  throw OutOfHostMemory(nmemb * size);
57  }
58  return ptr;
59 }
60 
62  void operator()(void* p) { free(p); }
63 };
64 
65 #endif // CHECKED_ALLOC_H
const std::string what_str_
Definition: checked_alloc.h:42
std::string to_string(char const *&&v)
void * checked_malloc(const size_t size)
Definition: checked_alloc.h:45
void * checked_calloc(const size_t nmemb, const size_t size)
Definition: checked_alloc.h:53
const char * what() const noexceptfinal
Definition: checked_alloc.h:39
void operator()(void *p)
Definition: checked_alloc.h:62
#define VLOG(n)
Definition: Logger.h:388
OutOfHostMemory(const size_t size)
Definition: checked_alloc.h:33