OmniSciDB  1dac507f6e
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
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 "../Shared/types.h"
28 #include "Shared/Logger.h"
29 
30 class OutOfHostMemory : public std::runtime_error {
31  public:
32  OutOfHostMemory(const size_t size)
33  : std::runtime_error("Failed to allocate " + std::to_string(size) +
34  " bytes of memory") {
35  VLOG(1) << "Failed to allocate " << size << " bytes " << std::endl
36  << boost::stacktrace::stacktrace();
37  }
38 };
39 
40 inline void* checked_malloc(const size_t size) {
41  auto ptr = malloc(size);
42  if (!ptr) {
43  throw OutOfHostMemory(size);
44  }
45  return ptr;
46 }
47 
48 inline void* checked_calloc(const size_t nmemb, const size_t size) {
49  auto ptr = calloc(nmemb, size);
50  if (!ptr) {
51  throw OutOfHostMemory(nmemb * size);
52  }
53  return ptr;
54 }
55 
57  void operator()(void* p) { free(p); }
58 };
59 
60 #endif // CHECKED_ALLOC_H
std::string to_string(char const *&&v)
void * checked_malloc(const size_t size)
Definition: checked_alloc.h:40
void * checked_calloc(const size_t nmemb, const size_t size)
Definition: checked_alloc.h:48
void operator()(void *p)
Definition: checked_alloc.h:57
#define VLOG(n)
Definition: Logger.h:280
OutOfHostMemory(const size_t size)
Definition: checked_alloc.h:32