1 // This file is part of Eigen, a lightweight C++ template library 2 // for linear algebra. 3 // 4 // Copyright (C) 2011 Benoit Jacob <jacob.benoit.1 (at) gmail.com> 5 // 6 // This Source Code Form is subject to the terms of the Mozilla 7 // Public License v. 2.0. If a copy of the MPL was not distributed 8 // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. 9 10 #include "main.h" 11 12 #define VERIFY_THROWS_BADALLOC(a) { \ 13 bool threw = false; \ 14 try { \ 15 a; \ 16 } \ 17 catch (std::bad_alloc&) { threw = true; } \ 18 VERIFY(threw && "should have thrown bad_alloc: " #a); \ 19 } 20 21 template<typename MatrixType> 22 void triggerMatrixBadAlloc(Index rows, Index cols) 23 { 24 VERIFY_THROWS_BADALLOC( MatrixType m(rows, cols) ); 25 VERIFY_THROWS_BADALLOC( MatrixType m; m.resize(rows, cols) ); 26 VERIFY_THROWS_BADALLOC( MatrixType m; m.conservativeResize(rows, cols) ); 27 } 28 29 template<typename VectorType> 30 void triggerVectorBadAlloc(Index size) 31 { 32 VERIFY_THROWS_BADALLOC( VectorType v(size) ); 33 VERIFY_THROWS_BADALLOC( VectorType v; v.resize(size) ); 34 VERIFY_THROWS_BADALLOC( VectorType v; v.conservativeResize(size) ); 35 } 36 37 void test_sizeoverflow() 38 { 39 // there are 2 levels of overflow checking. first in PlainObjectBase.h we check for overflow in rows*cols computations. 40 // this is tested in tests of the form times_itself_gives_0 * times_itself_gives_0 41 // Then in Memory.h we check for overflow in size * sizeof(T) computations. 42 // this is tested in tests of the form times_4_gives_0 * sizeof(float) 43 44 size_t times_itself_gives_0 = size_t(1) << (8 * sizeof(Index) / 2); 45 VERIFY(times_itself_gives_0 * times_itself_gives_0 == 0); 46 47 size_t times_4_gives_0 = size_t(1) << (8 * sizeof(Index) - 2); 48 VERIFY(times_4_gives_0 * 4 == 0); 49 50 size_t times_8_gives_0 = size_t(1) << (8 * sizeof(Index) - 3); 51 VERIFY(times_8_gives_0 * 8 == 0); 52 53 triggerMatrixBadAlloc<MatrixXf>(times_itself_gives_0, times_itself_gives_0); 54 triggerMatrixBadAlloc<MatrixXf>(times_itself_gives_0 / 4, times_itself_gives_0); 55 triggerMatrixBadAlloc<MatrixXf>(times_4_gives_0, 1); 56 57 triggerMatrixBadAlloc<MatrixXd>(times_itself_gives_0, times_itself_gives_0); 58 triggerMatrixBadAlloc<MatrixXd>(times_itself_gives_0 / 8, times_itself_gives_0); 59 triggerMatrixBadAlloc<MatrixXd>(times_8_gives_0, 1); 60 61 triggerVectorBadAlloc<VectorXf>(times_4_gives_0); 62 63 triggerVectorBadAlloc<VectorXd>(times_8_gives_0); 64 } 65