I am trying to read characters from a socket; here is the function I created for this, largely inspired from Here, where I remove some unrelevant parts here (this sample is compiling correctly).
int process(int socketfd, void *buffer, int n)
{
int totread = 0;
char ch;
int numread;
for(;;)
{
numread = read(socketfd, &ch, 1);
if(numread == 0) {
if (totread == 0) {
return 0;
} else {
break;
}
} else {
if(totread < n-1) {
totread++;
printf("totread: %d\n", totread);
printf("Here is OK, ch value gets printed %c\n", ch);
*buffer++ = ch;
printf("With help provided, this line gets printed\n");
printf("But the value <%s> of buffer, is blank (<> output)\n, buffer);
}
if (ch == '\n') {
printf("%c\n", ch);
printf("%s\n", buffer);
break;
}
}
}
return totread;
}
I can't understand why the second line does not get printed.
Obviously, the *buf++ = ch instruction is faulty; But it looks like correct. It simply affects the character read to the next value of the array of characters buf. I don't see errors or warnings at compile time, the client disconnects after the first line gets printed, and the second one is not reached.
EDIT
Here is how I initialize my buffer:
char *buffer = "";
int l = process(newsockfd, buffer, 100);
printf("Number read (function network) %d\n", l);
This is probably not the appropriate way to do it; I have also tried specifying a fixed length such as char buffer = [255]; The function does not exit then but nothing get printed. I'm quite a newbie in C programming, many thanks for your help!
bufwhenbufis eitherNULLor invalid memory. What happens when you run it undergdb, having compiled with-gto include debugging symbols?n(passed in) for?