scoder
scoder

Reputation: 2611

c++ exception convert from string to c_str creates Junk chars

I have a code like below:

class BaseException : public std::exception {
 private:
  string myexception;

   public:
  BaseException(string str):myexception(str){}
   virtual const char* what() const throw()  { return myexception.c_str();}

  string getMyexceptionStr() { return myexception};
  }

  class CustomException1 : public std::exception {
   public:
  CustomException1(string str):BaseException("CustomException1:"+str){}
   virtual const char* what() const throw()  { return getMyexceptionStr().c_str();}
  }

  class CustomException2 : public std::exception {
   public:
  CustomException2(string str):BaseException("CustomException2:" + str){}
   virtual const char* what() const throw()  { return getMyexceptionStr().c_str();}
  }


    void TestException1(){
    throw CustomException2("Caught in ");
  }

  void TestException2(){
    throw CustomException2("Caught in ");
  }

  int main(){

  try{
  TestException1();
  }
  catch(BaseException &e){
  cout << e.what();
  }

    try{
  TestException2();
  }
  catch(BaseException &e){
  cout << e.what();
  }

  }

Whenever I run the this I get below code of code

▒g▒▒▒g▒▒Exception1:Caught in

▒g▒▒▒g▒▒EException2:Caught in

I am returning the member variable in the same class context, the scope should be exist, but still I am getting junk chars.

What are the best way to handle it inorder to avoid Junk chars?

Due to some restriction I can not to use malloc or strdup while returning the exception

Upvotes: 1

Views: 322

Answers (1)

rustyx
rustyx

Reputation: 85341

string getMyexceptionStr() { return myexception; } - this returns a copy of myexception in a temporary string.

const char* what() { return getMyexceptionStr().c_str(); } - this returns a dangling pointer because the temporary string is destroyed at ;.

Change getMyexceptionStr() to return const string& instead.

Upvotes: 4

Related Questions