I have manualy writing class for WinSock. My program have more that one threads. I use to synchronize objects(example std::queue) with critical sections.
But I have errors in my socket class:
iResult = getaddrinfo(host.c_str(), port.c_str(), &hints, &(*this).addrresult); //permision error
In single thread mode all is OK. But if I start more that one threads, program has error. Help me.
int jSocket::ConnectSock(const std::string host, const std::string port)
{
int iResult;
struct addrinfo hints, *ptr;
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
iResult = getaddrinfo(host.c_str(), port.c_str(), &hints, &(*this).addrresult);
if (iResult != 0)
{
WSACleanup();
return -1;
}
ptr = (*this).addrresult;
(*this).sock = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);
if ((*this).sock == INVALID_SOCKET)
{
freeaddrinfo(addrresult);
WSACleanup();
return -1;
}
iResult = connect((*this).sock, ptr->ai_addr, (int)ptr->ai_addrlen);
if (iResult == SOCKET_ERROR)
{
closesocket((*this).sock);
return -1;
}
return 0;
}
Sorry for my English.
It looks like a race on the
addrresultmember pointer. The method you posted is not re-entrant since it updates member variables. If you call it concurrently from multiple threads you get surprises. I’m guessing in this particular case theaddrresultmight be allocated in one thread, then allocated and overwritten in another. You might end up with a memory leak and with access tofree-ed memory.