当我以字符串作为缓冲区开始async_write()时,我不确定为什么会出现分段错误。我过去成功使用过这个功能。
以下是我获得分段错误的方法:
void StringSocket::sendLine(const string& toWrite)
{
try
{
std::cout << "in StringSocket::sendLine()\n";
std::cout << "is the socket alive?: " << (bool)s->is_open() << "\n";
std::cout << "toWrite: " << toWrite;
//s = asio::ip::tcp::socket*
asio::async_write(*this->s,
asio::buffer(toWrite),
boost::bind(&StringSocket::MessageSent,
this,
asio::placeholders::error));
std::cout << "AFTER: asio::async_write()\n";
}
catch (int e)
{
std::cout << "ERROR: " << e << "\n";
}
}
这是编译器所说的:
in main()
in serverTCP::serverTCP()!
in spreadsheet::spreadsheet()
in serverTCP::start_accept()!
in client::client(asio::io_service& io_service, std::string name)
in StringSocket::StringSocket(asio::ip::tcp::socket *_socket)
in client::getSocket()
in StringSocket::underSoc()
in serverTCP::pickSpreadsheet()!
in client::getClientName()
in client::sendToGui(std::string mess)
in StringSocket::beginSend(const string& toWrite, sendCallback callBack, void* payload)
toWrite: Welcome to SS! user: user0000
in StringSocket::ProcessSend()
TextToSend: Welcome to SS! user: user0000
in StringSocket::sendLine()
is the socket alive?: 1
toWrite: Welcome to SS! user: user0000
Segmentation fault
答案 0 :(得分:1)
asio::async_write(*this->s, asio::buffer(toWrite),...
请注意,asio::buffer
只是一个不会复制其参数的适配器。因此,在上面的行中,您实际上将 local 对象作为缓冲区传递给async。操作。因此,toWrite
寿命和异步之间存在竞争条件。操作
答案 1 :(得分:0)
如果检查async_write
的引用(所有重载在此主题上都表示相同),它将告诉您处理函数有两个参数,首先是错误代码,然后是发送数据的长度。
您的boost::bind
来电仅提供一个参数。您仍然必须告诉boost::bind
有一个额外的参数将在稍后填写。您可以使用占位符参数boost::asio::placeholders::bytes_transferred
:
所以把它改成例如。
boost::bind(&StringSocket::MessageSent,
this,
asio::placeholders::error,
asio::placeholders::bytes_transferred)