PR c++/80290
[official-gcc.git] / gcc / testsuite / g++.dg / init / new39.C
blobf274ebb7b9d69e599225a77269b3cdf0593fa136
1 // Testcase for overflow handling in operator new[].
2 // { dg-do run }
4 #include <stdlib.h>
5 #include <stdexcept>
7 struct without_new {
8   char bar[256];
9 };
11 struct with_new {
12   char bar[256];
13   void *operator new[] (size_t sz)
14   {
15     if (sz != -1)
16       abort ();
17     throw std::bad_alloc();
18   }
21 template <typename T>
22 inline void
23 test (size_t s)
25   try {
26     new T[s];
27     abort ();
28   } catch (std::bad_alloc &) {
29   }
32 template <typename T>
33 void
34 test_noopt (size_t s) __attribute__((noinline));
36 template <typename T>
37 void
38 test_noopt (size_t s)
40   __asm__ ("");
41   test<T> (s);
44 template <typename T>
45 void
46 all_tests ()
48   test<T>(-1);
49   test<T>(size_t(-1) / sizeof (T) + 1);
50   test<T>(size_t(-1) / sizeof (T) + 2);
51   test_noopt<T>(-1);
52   test_noopt<T>(size_t(-1) / sizeof (T) + 1);
53   test_noopt<T>(size_t(-1) / sizeof (T) + 2);
56 int
57 main ()
59   try {
60     ::operator new(size_t(-1));
61     abort ();
62   } catch (std::bad_alloc &) {
63   }
64   all_tests<without_new> ();
65   all_tests<with_new> ();
66   return 0;