You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
2.6 KiB

  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. #include "main.h"
  10. #define VERIFY_THROWS_BADALLOC(a) { \
  11. bool threw = false; \
  12. try { \
  13. a; \
  14. } \
  15. catch (std::bad_alloc&) { threw = true; } \
  16. VERIFY(threw && "should have thrown bad_alloc: " #a); \
  17. }
  18. typedef DenseIndex Index;
  19. template<typename MatrixType>
  20. void triggerMatrixBadAlloc(Index rows, Index cols)
  21. {
  22. VERIFY_THROWS_BADALLOC( MatrixType m(rows, cols) );
  23. VERIFY_THROWS_BADALLOC( MatrixType m; m.resize(rows, cols) );
  24. VERIFY_THROWS_BADALLOC( MatrixType m; m.conservativeResize(rows, cols) );
  25. }
  26. template<typename VectorType>
  27. void triggerVectorBadAlloc(Index size)
  28. {
  29. VERIFY_THROWS_BADALLOC( VectorType v(size) );
  30. VERIFY_THROWS_BADALLOC( VectorType v; v.resize(size) );
  31. VERIFY_THROWS_BADALLOC( VectorType v; v.conservativeResize(size) );
  32. }
  33. void test_sizeoverflow()
  34. {
  35. // there are 2 levels of overflow checking. first in PlainObjectBase.h we check for overflow in rows*cols computations.
  36. // this is tested in tests of the form times_itself_gives_0 * times_itself_gives_0
  37. // Then in Memory.h we check for overflow in size * sizeof(T) computations.
  38. // this is tested in tests of the form times_4_gives_0 * sizeof(float)
  39. size_t times_itself_gives_0 = size_t(1) << (8 * sizeof(Index) / 2);
  40. VERIFY(times_itself_gives_0 * times_itself_gives_0 == 0);
  41. size_t times_4_gives_0 = size_t(1) << (8 * sizeof(Index) - 2);
  42. VERIFY(times_4_gives_0 * 4 == 0);
  43. size_t times_8_gives_0 = size_t(1) << (8 * sizeof(Index) - 3);
  44. VERIFY(times_8_gives_0 * 8 == 0);
  45. triggerMatrixBadAlloc<MatrixXf>(times_itself_gives_0, times_itself_gives_0);
  46. triggerMatrixBadAlloc<MatrixXf>(times_itself_gives_0 / 4, times_itself_gives_0);
  47. triggerMatrixBadAlloc<MatrixXf>(times_4_gives_0, 1);
  48. triggerMatrixBadAlloc<MatrixXd>(times_itself_gives_0, times_itself_gives_0);
  49. triggerMatrixBadAlloc<MatrixXd>(times_itself_gives_0 / 8, times_itself_gives_0);
  50. triggerMatrixBadAlloc<MatrixXd>(times_8_gives_0, 1);
  51. triggerVectorBadAlloc<VectorXf>(times_4_gives_0);
  52. triggerVectorBadAlloc<VectorXd>(times_8_gives_0);
  53. }