Debian Codegraph @

gcc/testsuite/g++.dg/init/new40.C

raw
1 // Testcase for overflow handling in operator new[].
2 // Optimization of unnecessary overflow checks.
3 // In C++11 we throw bad_array_new_length instead.
4 // { dg-options -std=c++03 }
5 // { dg-do run }
6 // { dg-xfail-run-if "AIX operator new" { powerpc-ibm-aix* } }
7 // { dg-skip-if "requires hosted libstdc++ for stdexcept" { ! hostedlib } }
8
9 #include <assert.h>
10 #include <stdlib.h>
11 #include <stdexcept>
12
13 static size_t magic_allocation_size
14 = 1 + (size_t (1) << (sizeof (size_t) * 8 - 1));
15
16 struct exc : std::bad_alloc {
17 };
18
19 static size_t expected_size;
20
21 struct pod_with_new {
22 char ch;
23 void *operator new[] (size_t sz)
24 {
25 if (sz != expected_size)
26 abort ();
27 throw exc ();
28 }
29 };
30
31 struct with_new {
32 char ch;
33 with_new () { }
34 ~with_new () { }
35 void *operator new[] (size_t sz)
36 {
37 if (sz != size_t (-1))
38 abort ();
39 throw exc ();
40 }
41 };
42
43 struct non_pod {
44 char ch;
45 non_pod () { }
46 ~non_pod () { }
47 };
48
49 void *
50 operator new (size_t sz) _GLIBCXX_THROW (std::bad_alloc)
51 {
52 if (sz != expected_size)
53 abort ();
54 throw exc ();
55 }
56
57 int
58 main ()
59 {
60 if (sizeof (pod_with_new) == 1)
61 expected_size = magic_allocation_size;
62 else
63 expected_size = -1;
64
65 try {
66 new pod_with_new[magic_allocation_size];
67 abort ();
68 } catch (exc &) {
69 }
70
71 if (sizeof (with_new) == 1)
72 expected_size = magic_allocation_size;
73 else
74 expected_size = -1;
75
76 try {
77 new with_new[magic_allocation_size];
78 abort ();
79 } catch (exc &) {
80 }
81
82 expected_size = magic_allocation_size;
83 try {
84 new char[magic_allocation_size];
85 abort ();
86 } catch (exc &) {
87 }
88
89 expected_size = -1;
90
91 try {
92 new pod_with_new[magic_allocation_size][2];
93 abort ();
94 } catch (exc &) {
95 }
96
97 try {
98 new with_new[magic_allocation_size][2];
99 abort ();
100 } catch (exc &) {
101 }
102
103 try {
104 new char[magic_allocation_size][2];
105 abort ();
106 } catch (exc &) {
107 }
108
109 try {
110 new non_pod[magic_allocation_size];
111 abort ();
112 } catch (exc &) {
113 }
114
115 return 0;
116 }