Debian Codegraph @

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

raw
1 // Testcase for overflow handling in operator new[].
2 // { dg-do run }
3 // { dg-skip-if "requires hosted libstdc++ for stdexcept" { ! hostedlib } }
4
5 #include <stdlib.h>
6 #include <stdexcept>
7
8 struct without_new {
9 char bar[256];
10 };
11
12 struct with_new {
13 char bar[256];
14 void *operator new[] (size_t sz)
15 {
16 if (sz != -1)
17 abort ();
18 throw std::bad_alloc();
19 }
20 };
21
22 template <typename T>
23 inline void
24 test (size_t s)
25 {
26 try {
27 new T[s];
28 abort ();
29 } catch (std::bad_alloc &) {
30 }
31 }
32
33 template <typename T>
34 void
35 test_noopt (size_t s) __attribute__((noinline));
36
37 template <typename T>
38 void
39 test_noopt (size_t s)
40 {
41 __asm__ ("");
42 test<T> (s);
43 }
44
45 template <typename T>
46 void
47 all_tests ()
48 {
49 test<T>(-1);
50 test<T>(size_t(-1) / sizeof (T) + 1);
51 test<T>(size_t(-1) / sizeof (T) + 2);
52 test_noopt<T>(-1);
53 test_noopt<T>(size_t(-1) / sizeof (T) + 1);
54 test_noopt<T>(size_t(-1) / sizeof (T) + 2);
55 }
56
57 int
58 main ()
59 {
60 try {
61 (void) ::operator new(size_t(-1));
62 abort ();
63 } catch (std::bad_alloc &) {
64 }
65 all_tests<without_new> ();
66 all_tests<with_new> ();
67 return 0;
68 }
69