Home > database >  C string and char* difference in example
C string and char* difference in example

Time:07-25

This is from hackerrank "Inherited Code" example,

While this works and what() returns n, if I comment the return in what and uncomment the currently commented part what() returns junk.

They look the same to me, what is the difference?

/* Define the exception here */
struct BadLengthException : public exception {      
    public: 
    int num;
    string stra;
    BadLengthException(int n){
        this->num = n;
        this->stra = to_string(this->num);
    };
    
   const char * what () const throw () {

       return this->stra.c_str();


       //string a = to_string(this->num);
       //return  a.c_str();
   }
};

CodePudding user response:

string a is a local (ASDV) in what(). It goes out of scope when you return. a.c_str() is simply a pointer, it's non-owning and thus doesn't extend the lifetime of the char buffer, therefore it's UB. In case of UB, anything can happen, including returning junk.

  • Related