Piotr.Bratkowski
Piotr.Bratkowski

Reputation: 1

Code working inline, but when in class

I'm writing program using Boost::Asio, I want to implement simple chat. Currently I'm struggling with problem that when I put some code inline of class function it's working, but when same code is provided by another class object is not. I think it could be connected to Boost::Asio, but I'm not sure:

void Connection::session(socket_ptr sock)
{
 try{
  for(;;) {
  char mesg[1024];

  boost::system::error_code error;
  size_t length = sock->read_some(boost::asio::buffer(mesg), error);

  if (error == boost::asio::error::eof){
    disconnected(sock);
    break;
  }
  else if (error)
    throw boost::system::system_error(error);

  message msg(mesg,length);
  char *data;
  data = msg.getData();
  std::cout << "In session " << strlen(data) << " " << data;

/*This is working
  string s_msg,s_data;
  s_msg = mesg;
  s_data = s_msg.substr(2,length);
  std::vector<char> writable(s_data.size() + 1);
  std::copy(s_data.begin(), s_data.end(), writable.begin());
  std::cout << "In session " << strlen(&writable[0]) << " " << &writable[0];
  send_all(sock,&writable[0],strlen(&writable[0]));
*/

  send_all(sock,data,strlen(data));
  }
}
catch (std::exception& e){
   std::cerr << "Exception in thread: " << e.what() << "\n";
   }
 }

Class message that is only parsing data

  message::message(char *c_msg, size_t length)
   {
    msg = c_msg;
    id = msg.at(0);
    data = msg.substr(2,length);
    }

   char* message::getData()
   {
    std::vector<char> writable(data.size() + 1);
    std::copy(data.begin(), data.end(), writable.begin());

    std::cout << data;
    std::cout << &writable[0];
    return &writable[0];
   }

So when using class message this line:

std::cout << "In session " << strlen(data) << " " << data;

I get:

st String //this is cout from message getData
st String //this is cout from message getData
In session 0

With inline version:

In session 11 st String

So, in session function string is empty although message cout shows something opposite. I don't know if it's important, but this function is invoked as new thread from main.

Regards, Piotr

Upvotes: 0

Views: 70

Answers (1)

paddy
paddy

Reputation: 63481

You're returning the address of a temporary:

char* message::getData()
{
    std::vector<char> writable(data.size() + 1);
    //...
    return &writable[0];
}

This is undefined behaviour.

I'm assuming that data is just a std::string. You could do this instead:

const char* message::getData() const
{
    return data.c_str();
}

Upvotes: 1

Related Questions