From d35bbc25cdafeeedd5a2b2572b7f6f0cfb693329 Mon Sep 17 00:00:00 2001 From: Nick Lewycky Date: Sun, 21 Feb 2021 11:12:39 -0800 Subject: [PATCH] Return a valid pointer. stringstream::str() creates a temporary that is destroyed at the end of the full-expression (the semi-colon), and c_str() on that string returns a pointer internal to the string. This function returns a pointer to freed memory. Spotted by clang warning: ``` error.h:51:12: warning: returning address of local temporary object [-Wreturn-stack-address] return ss.str().c_str(); ^~~~~~~~ 1 warning generated. ``` --- src/validator/error.h | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/validator/error.h b/src/validator/error.h index 5c16e236d..1865d10c4 100644 --- a/src/validator/error.h +++ b/src/validator/error.h @@ -27,10 +27,11 @@ class validator_error : public std::exception { public: - validator_error(std::string file, int line, std::string message) { - file_ = file; - line_ = line; - message_ = message; + validator_error(std::string file, int line, std::string message) + : file_(file), line_(line), message_(message) { + std::stringstream ss; + ss << "[" << file_ << ":" << line_ << "] " << message_; + what_ = ss.str(); } int get_line() { @@ -46,9 +47,7 @@ class validator_error : public std::exception { } virtual const char* what() const throw() { - std::stringstream ss; - ss << "[" << file_ << ":" << line_ << "] " << message_; - return ss.str().c_str(); + return what_.c_str(); } private: @@ -56,6 +55,7 @@ class validator_error : public std::exception { std::string message_; std::string file_; int line_; + std::string what_; };