Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Weird string/char* exception behaviour

Well here is my exception code :

class OptionNotFoundError: public std::exception {
public:
    OptionNotFoundError(std::string option, int position) throw()
        : option(option), position(position) {}
    OptionNotFoundError(char option_, int position) throw()
        : position(position) { option.push_back(option_); }

    virtual ~OptionNotFoundError() throw() {}

    virtual const char* what() const throw() {
        std::string what_str = "Option '" + option + "' not found in position " + std::to_string(position);
        std::cout << what_str.c_str() << std::endl;
        return what_str.c_str();;
    }

    std::string option;
    int position;
};

When the exception is thrown, here is what I get in the terminal :

terminate called after throwing an instance of 'Args::OptionNotFoundError'
Option 'c' not found in position 1
  what():  

So the cout works fine, but… not the return. If I use return "smth" it works fine.

Weirder : if I replace what_str definition with

std::string what_str = "test";

I get

terminate called after throwing an instance of 'Args::OptionNotFoundError'
test
  what():  x�zL�

Again, the cout<< works fine. But the return… Not so much. Is this some encoding error ?

like image 270
Salamandar Avatar asked Dec 08 '25 04:12

Salamandar


1 Answers

    return what_str.c_str();;

c_str() returns a pointer to the internal contents of the std::string.

This pointer remains valid only until either

  1. The std::string object gets destroyed.

  2. The std::string object gets modified.

The std::string object from which this c_str() pointer is obtained gets destroyed when your function returns.

This results in undefined behavior.

The const char * that your function returns is not valid. It's pointing to the internal contents of a destroyed object.

like image 81
Sam Varshavchik Avatar answered Dec 10 '25 19:12

Sam Varshavchik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!