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.

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