My application is crashing when I try printing the buffer. Otherwise, it works fine.
This is the code:
irc.h
class IRC
{
public:
void sockconnect(char * hName, int portNum);
void sockwrite(char* sendbuf);
char sockread(void);
bool connected;
private:
WSADATA wsaData;
SOCKET m_socket;
sockaddr_in clientService;
LPHOSTENT hostEntry;
};
irc.cc
char IRC::sockread(void)
{
int result;
char buffer[DEFAULT_BUFLEN];
result = recv(m_socket, buffer, DEFAULT_BUFLEN, 0);
if (result > 0) {
return *buffer;
}
else if (result == 0)
{
connected = false;
return *buffer;
}
else {
printf("recv failed with error: %d\n", WSAGetLastError());
return *buffer;
}
}
main.cc
IRC client;
while (client.connected == true) {
char buffer = client.sockread();
if (buffer == NULL)
break;
printf ("Buffer: %s\n",buffer);
}
If you want to print the first character use
If you want to print the whole then sockread should return the whole buffer, not the first character. For that you will need to return the address of the first element of the buffer which in this case should already be dynamically allocated.
Edit After thinking I think you want the latter for that change the
sockread()function in the following way:chartochar*or betterconst char*char buffer[DEFAULT_BUFLEN];tochar* buffer = new char[DEFAULT_BUFLEN];return *buffertoreturn bufferAlso, in this case don’t forget to delete the buffer
hth