1 // Testcase for overflow handling in operator new[]. 2 // { dg-do run } 3 4 #include <stdlib.h> 5 #include <stdexcept> 6 7 struct without_new { 8 char bar[256]; 9 }; 10 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 } 19 }; 20 21 template <typename T> 22 inline void test(size_t s)23test (size_t s) 24 { 25 try { 26 new T[s]; 27 abort (); 28 } catch (std::bad_alloc &) { 29 } 30 } 31 32 template <typename T> 33 void 34 test_noopt (size_t s) __attribute__((noinline)); 35 36 template <typename T> 37 void test_noopt(size_t s)38test_noopt (size_t s) 39 { 40 __asm__ (""); 41 test<T> (s); 42 } 43 44 template <typename T> 45 void all_tests()46all_tests () 47 { 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); 54 } 55 56 int main()57main () 58 { 59 try { 60 (void) ::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; 67 } 68 69