diff --git a/src/cxx.cc b/src/cxx.cc index 4958eb08b..c630647b7 100644 --- a/src/cxx.cc +++ b/src/cxx.cc @@ -448,9 +448,14 @@ static_assert(!std::is_same::const_iterator, Vec::iterator>::value, "Vec::const_iterator != Vec::iterator"); -static const char *errorCopy(const char *ptr, std::size_t len) { - char *copy = new char[len]; - std::memcpy(copy, ptr, len); +// Copy the error message into a private buffer and return it. +// If the allocation fails, nullptr is returned. +static const char *errorCopy(const char *ptr, std::size_t len) noexcept { + char *copy = new (std::nothrow) char[len + 1]; + if (copy) { + std::memcpy(copy, ptr, len); + copy[len] = 0; + } return copy; } @@ -496,7 +501,12 @@ Error &Error::operator=(Error &&other) &noexcept { return *this; } -const char *Error::what() const noexcept { return this->msg; } +const char *Error::what() const noexcept { + if (this->msg) + return this->msg; + else + return ""; +} namespace { template