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// asan and msan will not call the new handler.
12// UNSUPPORTED: sanitizer-new-delete
13
14#include <new>
15#include <cstddef>
16#include <cassert>
17#include <limits>
18
19#include "test_macros.h"
20#include "../types.h"
21
22int new_handler_called = 0;
23
24void my_new_handler() {
25 ++new_handler_called;
26 std::set_new_handler(nullptr);
27}
28
29int main(int, char**) {
30 // Test that we can call the function directly
31 {
32 void* x = operator new[](10);
33 assert(x != nullptr);
34 operator delete[](x);
35 }
36
37 // Test that the new handler is called if allocation fails
38 {
39#ifndef TEST_HAS_NO_EXCEPTIONS
40 std::set_new_handler(my_new_handler);
41 try {
42 void* x = operator new[] (std::numeric_limits<std::size_t>::max());
43 (void)x;
44 assert(false);
45 }
46 catch (std::bad_alloc const&) {
47 assert(new_handler_called == 1);
48 } catch (...) {
49 assert(false);
50 }
51#endif
52 }
53
54 // Test that a new expression constructs the right objects
55 // and a delete expression deletes them. The brace-init requires C++11.
56 {
57#if TEST_STD_VER >= 11
58 LifetimeInformation infos[3];
59 TrackLifetime* x = new TrackLifetime[3]{infos[0], infos[1], infos[2]};
60 assert(x != nullptr);
61
62 void* addresses[3] = {&x[0], &x[1], &x[2]};
63 assert(infos[0].address_constructed == addresses[0]);
64 assert(infos[1].address_constructed == addresses[1]);
65 assert(infos[2].address_constructed == addresses[2]);
66
67 delete[] x;
68 assert(infos[0].address_destroyed == addresses[0]);
69 assert(infos[1].address_destroyed == addresses[1]);
70 assert(infos[2].address_destroyed == addresses[2]);
71#endif
72 }
73
74 return 0;
75}
76

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