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// XFAIL: libcpp-no-vcruntime
15
16#include <new>
17#include <cstddef>
18#include <cstdlib>
19#include <cassert>
20#include <limits>
21
22#include "test_macros.h"
23
24int new_called = 0;
25int delete_called = 0;
26
27void* operator new[](std::size_t s) TEST_THROW_SPEC(std::bad_alloc) {
28 ++new_called;
29 void* ret = std::malloc(s);
30 if (!ret) {
31 std::abort(); // placate MSVC's unchecked malloc warning (assert() won't silence it)
32 }
33 return ret;
34}
35
36void operator delete[](void* p) TEST_NOEXCEPT {
37 ++delete_called;
38 std::free(p);
39}
40
41int main(int, char**) {
42 new_called = delete_called = 0;
43 int* x = DoNotOptimize(new int[3]);
44 assert(x != nullptr);
45 ASSERT_WITH_OPERATOR_NEW_FALLBACKS(new_called == 1);
46
47 delete[] x;
48 ASSERT_WITH_OPERATOR_NEW_FALLBACKS(delete_called == 1);
49
50 return 0;
51}
52

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