blob: ed076ffa52d6012c42f7fbf487aae59571ba7693 [file] [log] [blame]
Andrew Scullcdfcccc2018-10-05 20:58:37 +01001//===- MemAlloc.h - Memory allocation functions -----------------*- C++ -*-===//
2//
Andrew Walbran16937d02019-10-22 13:54:20 +01003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Andrew Scullcdfcccc2018-10-05 20:58:37 +01006//
7//===----------------------------------------------------------------------===//
8/// \file
9///
10/// This file defines counterparts of C library allocation functions defined in
11/// the namespace 'std'. The new allocation functions crash on allocation
12/// failure instead of returning null pointer.
13///
14//===----------------------------------------------------------------------===//
15
16#ifndef LLVM_SUPPORT_MEMALLOC_H
17#define LLVM_SUPPORT_MEMALLOC_H
18
19#include "llvm/Support/Compiler.h"
20#include "llvm/Support/ErrorHandling.h"
21#include <cstdlib>
22
23namespace llvm {
24
25LLVM_ATTRIBUTE_RETURNS_NONNULL inline void *safe_malloc(size_t Sz) {
26 void *Result = std::malloc(Sz);
27 if (Result == nullptr)
28 report_bad_alloc_error("Allocation failed");
29 return Result;
30}
31
32LLVM_ATTRIBUTE_RETURNS_NONNULL inline void *safe_calloc(size_t Count,
33 size_t Sz) {
34 void *Result = std::calloc(Count, Sz);
35 if (Result == nullptr)
36 report_bad_alloc_error("Allocation failed");
37 return Result;
38}
39
40LLVM_ATTRIBUTE_RETURNS_NONNULL inline void *safe_realloc(void *Ptr, size_t Sz) {
41 void *Result = std::realloc(Ptr, Sz);
42 if (Result == nullptr)
43 report_bad_alloc_error("Allocation failed");
44 return Result;
45}
46
47}
48#endif