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 8 #include <assert.h> 9 #include <stdlib.h> 10 #include <stdexcept> 11 12 static size_t magic_allocation_size 13 = 1 + (size_t (1) << (sizeof (size_t) * 8 - 1)); 14 15 struct exc : std::bad_alloc { 16 }; 17 18 static size_t expected_size; 19 20 struct pod_with_new { 21 char ch; 22 void *operator new[] (size_t sz) 23 { 24 if (sz != expected_size) 25 abort (); 26 throw exc (); 27 } 28 }; 29 30 struct with_new { 31 char ch; with_newwith_new32 with_new () { } ~with_newwith_new33 ~with_new () { } 34 void *operator new[] (size_t sz) 35 { 36 if (sz != size_t (-1)) 37 abort (); 38 throw exc (); 39 } 40 }; 41 42 struct non_pod { 43 char ch; non_podnon_pod44 non_pod () { } ~non_podnon_pod45 ~non_pod () { } 46 }; 47 48 void * new(size_t sz)49operator new (size_t sz) _GLIBCXX_THROW (std::bad_alloc) 50 { 51 if (sz != expected_size) 52 abort (); 53 throw exc (); 54 } 55 56 int main()57main () 58 { 59 if (sizeof (pod_with_new) == 1) 60 expected_size = magic_allocation_size; 61 else 62 expected_size = -1; 63 64 try { 65 new pod_with_new[magic_allocation_size]; 66 abort (); 67 } catch (exc &) { 68 } 69 70 if (sizeof (with_new) == 1) 71 expected_size = magic_allocation_size; 72 else 73 expected_size = -1; 74 75 try { 76 new with_new[magic_allocation_size]; 77 abort (); 78 } catch (exc &) { 79 } 80 81 expected_size = magic_allocation_size; 82 try { 83 new char[magic_allocation_size]; 84 abort (); 85 } catch (exc &) { 86 } 87 88 expected_size = -1; 89 90 try { 91 new pod_with_new[magic_allocation_size][2]; 92 abort (); 93 } catch (exc &) { 94 } 95 96 try { 97 new with_new[magic_allocation_size][2]; 98 abort (); 99 } catch (exc &) { 100 } 101 102 try { 103 new char[magic_allocation_size][2]; 104 abort (); 105 } catch (exc &) { 106 } 107 108 try { 109 new non_pod[magic_allocation_size]; 110 abort (); 111 } catch (exc &) { 112 } 113 114 return 0; 115 } 116