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@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 21typedef DenseIndex Index; 22 23template<typename MatrixType> 24void triggerMatrixBadAlloc(Index rows, Index cols) 25{ 26 VERIFY_THROWS_BADALLOC( MatrixType m(rows, cols) ); 27 VERIFY_THROWS_BADALLOC( MatrixType m; m.resize(rows, cols) ); 28 VERIFY_THROWS_BADALLOC( MatrixType m; m.conservativeResize(rows, cols) ); 29} 30 31template<typename VectorType> 32void triggerVectorBadAlloc(Index size) 33{ 34 VERIFY_THROWS_BADALLOC( VectorType v(size) ); 35 VERIFY_THROWS_BADALLOC( VectorType v; v.resize(size) ); 36 VERIFY_THROWS_BADALLOC( VectorType v; v.conservativeResize(size) ); 37} 38 39void test_sizeoverflow() 40{ 41 // there are 2 levels of overflow checking. first in PlainObjectBase.h we check for overflow in rows*cols computations. 42 // this is tested in tests of the form times_itself_gives_0 * times_itself_gives_0 43 // Then in Memory.h we check for overflow in size * sizeof(T) computations. 44 // this is tested in tests of the form times_4_gives_0 * sizeof(float) 45 46 size_t times_itself_gives_0 = size_t(1) << (8 * sizeof(Index) / 2); 47 VERIFY(times_itself_gives_0 * times_itself_gives_0 == 0); 48 49 size_t times_4_gives_0 = size_t(1) << (8 * sizeof(Index) - 2); 50 VERIFY(times_4_gives_0 * 4 == 0); 51 52 size_t times_8_gives_0 = size_t(1) << (8 * sizeof(Index) - 3); 53 VERIFY(times_8_gives_0 * 8 == 0); 54 55 triggerMatrixBadAlloc<MatrixXf>(times_itself_gives_0, times_itself_gives_0); 56 triggerMatrixBadAlloc<MatrixXf>(times_itself_gives_0 / 4, times_itself_gives_0); 57 triggerMatrixBadAlloc<MatrixXf>(times_4_gives_0, 1); 58 59 triggerMatrixBadAlloc<MatrixXd>(times_itself_gives_0, times_itself_gives_0); 60 triggerMatrixBadAlloc<MatrixXd>(times_itself_gives_0 / 8, times_itself_gives_0); 61 triggerMatrixBadAlloc<MatrixXd>(times_8_gives_0, 1); 62 63 triggerVectorBadAlloc<VectorXf>(times_4_gives_0); 64 65 triggerVectorBadAlloc<VectorXd>(times_8_gives_0); 66} 67