You have an error in socketRead()
here:
char *ch;
if(recv(sockfd, ch, 1, 0) == -1)
return -1;
ch
is only a pointer, you never allocated memory to store something in there - all you have is a pointer that was not initialized. You can't use it and pass it to recv
, because recv
will attempt to write to an undefined location. This is why your program crashes.
I think you want to use buffer
here:
if (recv(sockfd, buffer, sizeof buffer, 0) == -1) { ... }
Or, alternatively, you can make ch
point to a valid location before using it:
ch = buffer;
if (recv(sockfd, ch, sizeof buffer, 0) == -1) { ... }
Note, however, that in this case you can't use sizeof ch
, since that would yield the size of a char *
.
If you want to explicitly leave out space for a null terminating byte, then use sizeof(buffer) - 1
:
if (recv(sockfd, buffer, sizeof buffer, 0) == -1) { ... }
These lines are also wrong, for the same reason: you never initialized ch
strcat(buffer, ch);
if (*ch == '\n') {
Note that recv(sockfd, buffer, sizeof(buffer)-1, 0)
will read chunks of at most sizeof(buffer)-1
bytes. Your code conveys the idea that you want to read it char by char; in that case, you probably want to make ch
a char
instead of a char *
. In that case, you just have to use the address of operator in the call to recv
, because recv
expects a pointer:
if (recv(sockfd, &ch, 1, 0) == -1)
But then of course, you can't use strcat
with a char (strcat
expects null terminated sequences of characters), and instead of if (*ch == '\n')
, you must use if (ch == '\n')
.