Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ : Exception occurred in script: basic_string::_S_construct NULL not valid

Tags:

c++

linux

I am returning a string or NULL from the database function to the main program, sometimes i get this error from the exception:

basic_string::_S_construct NULL not valid

i think its because of the return NULL value from the database function? any ideas???

string database(string& ip, string& agent){
  //this is just for explanation
  .....
  ....

  return NULL or return string

}

int main(){
   string ip,host,proto,method,agent,request,newdec;
   httplog.open("/var/log/redirect/httplog.log", ios::app);

   try{
      ip = getenv("IP");
      host = getenv("CLIENT[host]");
      proto = getenv("HTTP_PROTO");
      method = getenv("HTTP_METHOD");
      agent = getenv("CLIENT[user-agent]");

      if (std::string::npos != host.find(string("dmnfmsdn.com")))
         return 0;

      if (std::string::npos != host.find(string("sdsdsds.com")))
         return 0;

      if (method=="POST")
         return 0;

      newdec = database(ip,agent);
      if (newdec.empty())
         return 0;
      else {
         httplog << "Redirecting to splash page for user IP: " << ip << endl;
         cout << newdec;
         cout.flush();
      }
      httplog.close();
      return 0; 
   }
   catch (exception& e){
      httplog << "Exception occurred in script: " << e.what() << endl;
      return 0;
   }
   return 0;
}
like image 568
krisdigitx Avatar asked Aug 21 '12 10:08

krisdigitx


3 Answers

You cannot return NULL (or 0) from a function that is declared to return string because there is no appropriate implicit conversion. You might want to return an empty string though

return string();

or

return "";

If you want to be able to distinguish between a NULL value and an empty string, then you will have to use either pointers (smart ones, preferrably), or, alternatively, you could use std::optional (or boost::optional before C++17).

like image 139
Armen Tsirunyan Avatar answered Nov 03 '22 14:11

Armen Tsirunyan


It's a violation of std::string's contract to construct it from a null char pointer. Just return an empty string if the pointer that you want to construct it from is null.

E.g.

return p == NULL ? std::string() : std::string(p);
like image 26
CB Bailey Avatar answered Nov 03 '22 14:11

CB Bailey


I would try changing it to return an empty string instead of null and check the string length.

like image 2
ddoor Avatar answered Nov 03 '22 16:11

ddoor