OmniSciDB  8a228a1076
checked_alloc.h
Go to the documentation of this file.
1 /*
2  * Copyright 2017 MapD Technologies, 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 
22 #include <boost/stacktrace.hpp>
23 #include <cstdlib>
24 #include <ostream>
25 #include <stdexcept>
26 #include <string>
27 #include "../Logger/Logger.h"
28 #include "../Shared/types.h"
29 
30 class OutOfHostMemory : public std::bad_alloc {
31  public:
32  OutOfHostMemory(const size_t size)
33  : what_str_("Not enough CPU memory available to allocate " + std::to_string(size)) {
34  VLOG(1) << "Failed to allocate " << size << " bytes " << std::endl
35  << boost::stacktrace::stacktrace();
36  }
37 
38  virtual const char* what() const noexcept final { return what_str_.c_str(); }
39 
40  private:
41  const std::string what_str_;
42 };
43 
44 inline void* checked_malloc(const size_t size) {
45  auto ptr = malloc(size);
46  if (!ptr) {
47  throw OutOfHostMemory(size);
48  }
49  return ptr;
50 }
51 
52 inline void* checked_calloc(const size_t nmemb, const size_t size) {
53  auto ptr = calloc(nmemb, size);
54  if (!ptr) {
55  throw OutOfHostMemory(nmemb * size);
56  }
57  return ptr;
58 }
59 
61  void operator()(void* p) { free(p); }
62 };
63 
64 #endif // CHECKED_ALLOC_H
const std::string what_str_
Definition: checked_alloc.h:41
std::string to_string(char const *&&v)
void * checked_malloc(const size_t size)
Definition: checked_alloc.h:44
void * checked_calloc(const size_t nmemb, const size_t size)
Definition: checked_alloc.h:52
void operator()(void *p)
Definition: checked_alloc.h:61
virtual const char * what() const noexcept final
Definition: checked_alloc.h:38
#define VLOG(n)
Definition: Logger.h:291
OutOfHostMemory(const size_t size)
Definition: checked_alloc.h:32