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 // test operator new [] (nothrow)
10 // NOTE: asan and msan will not call the new handler.
11 // UNSUPPORTED: sanitizer-new-delete
12 
13 
14 #include <new>
15 #include <cstddef>
16 #include <cassert>
17 #include <limits>
18 
19 #include "test_macros.h"
20 
21 int new_handler_called = 0;
22 
my_new_handler()23 void my_new_handler()
24 {
25     ++new_handler_called;
26     std::set_new_handler(0);
27 }
28 
29 int A_constructed = 0;
30 
31 struct A
32 {
AA33     A() {++A_constructed;}
~AA34     ~A() {--A_constructed;}
35 };
36 
main(int,char **)37 int main(int, char**)
38 {
39     new_handler_called = 0;
40     std::set_new_handler(my_new_handler);
41 #ifndef TEST_HAS_NO_EXCEPTIONS
42     try
43 #endif
44     {
45         void* vp = operator new [] (std::numeric_limits<std::size_t>::max(), std::nothrow);
46         DoNotOptimize(vp);
47         assert(new_handler_called == 1);
48         assert(vp == 0);
49     }
50 #ifndef TEST_HAS_NO_EXCEPTIONS
51     catch (...)
52     {
53         assert(false);
54     }
55 #endif
56     A* ap = new(std::nothrow) A[3];
57     DoNotOptimize(ap);
58     assert(ap);
59     assert(A_constructed == 3);
60     delete [] ap;
61     DoNotOptimize(ap);
62     assert(A_constructed == 0);
63 
64   return 0;
65 }
66