Guard all malloc, realloc and free() fonctions with check_that_malloc_is_allowed()
Context
Checking dynamic allocation at runtime for a specific check of code, using Eigen::internal::set_is_malloc_allowed(true|false)
Changing eigen_assert
to throw instead of aborting the program, (most unit c++ unit testing framework do not support std::abort()
)
#include <stdexcept>
#define eigen_assert(x) if(!(x)) throw(std::runtime_error("Assertion failed"));
#include <Eigen/Core>
ref: https://eigen.tuxfamily.org/dox/TopicAssertions.html
After #1055 (closed), the following code (using catch2) crashes on windows, due to the fact that memory has been reallocated successfully, but not returned due to the throw.
Eigen::VectorXd q(50);
REQUIRE_FALSE(Eigen::internal::set_is_malloc_allowed(false));
CHECK_THROWS(q.conservativeResizeLike(Eigen::VectorXd::Zero(350))); /// calls aligned_realloc(), next line crashes while trying to free the q variable.
REQUIRE(Eigen::internal::set_is_malloc_allowed(true)); /// next instruction is a crash as it is trying to free the reallocated-not-really q variable.
What does this implement/fix?
- The change introduced in !1055 (merged) only check after the memory was actually allocated, causing the free() function to behave unexpectedly (heap crashes on windows)
- Add guards for all malloc, realloc and free function, so user can detect ANY unwanted call in their application