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// GCC warns about allocating numeric_limits<size_t>::max() being too large (which we test here)
15// ADDITIONAL_COMPILE_FLAGS(gcc): -Wno-alloc-size-larger-than
16
17#include <new>
18#include <cstddef>
19#include <cassert>
20#include <limits>
21
22#include "test_macros.h"
23#include "../types.h"
24
25int new_handler_called = 0;
26
27void my_new_handler() {
28 ++new_handler_called;
29 std::set_new_handler(nullptr);
30}
31
32int main(int, char**) {
33 // Test that we can call the function directly
34 {
35 void* x = operator new(10);
36 assert(x != nullptr);
37 operator delete(x);
38 }
39
40 // Test that the new handler is called if allocation fails
41 {
42#ifndef TEST_HAS_NO_EXCEPTIONS
43 std::set_new_handler(my_new_handler);
44 try {
45 void* x = operator new(std::numeric_limits<std::size_t>::max());
46 (void)x;
47 assert(false);
48 } catch (std::bad_alloc const&) {
49 assert(new_handler_called == 1);
50 } catch (...) {
51 assert(false);
52 }
53#endif
54 }
55
56 // Test that a new expression constructs the right object
57 // and a delete expression deletes it
58 {
59 LifetimeInformation info;
60 TrackLifetime* x = new TrackLifetime(info);
61 assert(x != nullptr);
62 assert(info.address_constructed == x);
63
64 delete x;
65 assert(info.address_destroyed == x);
66 }
67
68 return 0;
69}
70

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