From 51470460cccadcaff9c748c6dfb615eff90569ae Mon Sep 17 00:00:00 2001 From: jediaz Date: Mon, 18 May 2020 12:48:26 +0200 Subject: [PATCH] #0 Replace reinterpret_cast used in binary I/O by a safer combination of std::vector and std::memcpy. #0 Add a header file required by gcc for std::memcpy. --- .../Wrappers/Petsc/Vector/Internal/VectorHelper.cpp | 6 +++++- Sources/Utilities/OutputFormat/ReadBinaryFile.cpp | 11 ++++++----- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/Sources/ThirdParty/Wrappers/Petsc/Vector/Internal/VectorHelper.cpp b/Sources/ThirdParty/Wrappers/Petsc/Vector/Internal/VectorHelper.cpp index 4289e52fd..19b658822 100644 --- a/Sources/ThirdParty/Wrappers/Petsc/Vector/Internal/VectorHelper.cpp +++ b/Sources/ThirdParty/Wrappers/Petsc/Vector/Internal/VectorHelper.cpp @@ -13,6 +13,7 @@ #include +#include // required by gcc for std::memcpy. #include "Utilities/Filesystem/File.hpp" #include "Utilities/OutputFormat/OutputFormat.hpp" @@ -58,7 +59,10 @@ namespace MoReFEM std::ofstream::binary); const auto array = content.GetArray(); - out.write(reinterpret_cast(array), Nvalue * sizeof(double)); + const auto Nbits = Nvalue * sizeof(double); + std::vector binary_values(Nbits); + std::memcpy(binary_values.data(), array, Nbits); + out.write(binary_values.data(), static_cast(Nbits)); out.close(); break; } diff --git a/Sources/Utilities/OutputFormat/ReadBinaryFile.cpp b/Sources/Utilities/OutputFormat/ReadBinaryFile.cpp index 99dd75c97..9945a071c 100644 --- a/Sources/Utilities/OutputFormat/ReadBinaryFile.cpp +++ b/Sources/Utilities/OutputFormat/ReadBinaryFile.cpp @@ -10,6 +10,7 @@ #include #include +#include // required by gcc for std::memcpy. #include "Utilities/Exceptions/Exception.hpp" #include "Utilities/OutputFormat/ReadBinaryFile.hpp" @@ -46,12 +47,12 @@ namespace MoReFEM::Advanced in.close(); - // Buffer contains the entire file. Convert bytes back into doubles. - const double * values = reinterpret_cast (buffer.data()); + // Buffer contains the entire file. Convert bytes back into doubles. + const unsigned long Ndouble_values = static_cast(block_size) / sizeof(double); + std::vector values(Ndouble_values); + std::memcpy(values.data(), buffer.data(), static_cast(block_size)); - const unsigned long Nvalue_binary = static_cast(block_size) / sizeof(double); - - for (std::size_t i = 0u; i < Nvalue_binary; ++i) + for (std::size_t i = 0u; i < Ndouble_values; ++i) { if (std::fabs(values[i]) <= epsilon) ret.push_back(0.); -- GitLab