1//===----------------------------------------------------------------------===//
2//
3// 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
6//
7//===----------------------------------------------------------------------===//
8
9// void* operator new(std::size_t);
10
11// Test that we can replace the operator by defining our own.
12
13// UNSUPPORTED: sanitizer-new-delete
14
15#include <new>
16#include <cstddef>
17#include <cstdlib>
18#include <cassert>
19
20#include "test_macros.h"
21
22int new_called = 0;
23int delete_called = 0;
24
25void* operator new(std::size_t s) TEST_THROW_SPEC(std::bad_alloc) {
26 ++new_called;
27 void* ret = std::malloc(s);
28 if (!ret) {
29 std::abort(); // placate MSVC's unchecked malloc warning (assert() won't silence it)
30 }
31 return ret;
32}
33
34void operator delete(void* p) TEST_NOEXCEPT {
35 ++delete_called;
36 std::free(p);
37}
38
39int main(int, char**) {
40 new_called = delete_called = 0;
41 int* x = DoNotOptimize(new int(3));
42 assert(x != nullptr);
43 ASSERT_WITH_OPERATOR_NEW_FALLBACKS(new_called == 1);
44
45 delete x;
46 ASSERT_WITH_OPERATOR_NEW_FALLBACKS(delete_called == 1);
47
48 return 0;
49}
50

source code of libcxx/test/std/language.support/support.dynamic/new.delete/new.delete.single/new.size.replace.pass.cpp