Search code examples
csocketsclientserverread-write

C Socket Programming write/read dirty memory


I wrote two custom function for write and read on my C program that my university teacher suggested:

ssize_t FullRead(int fd, void *buff, size_t count) {
    size_t nleft;
    ssize_t nread;
    nleft = count;
    while(nleft > 0) {
        nread = read(fd, buff, nleft);
        if(errno == EINTR) {
            continue;
        }
        else {
            return nread;
        }
        if(nread == 0) {
            break;
        }
        nleft -= nread;
        buff += nread;
    }
    buff = 0;
    return nleft;
}

And

ssize_t FullWrite(int fd, const void *buff, size_t count) {
    size_t nleft;
    ssize_t nwritten;
    nleft = count;
    while(nleft > 0) {
        if((nwritten=write(fd, buff, nleft)) < 0) {
            if(errno == EINTR) {
                continue;
            }
            else {
                return nwritten;
            }
        }
        nleft -= nwritten;
        buff += nwritten;
    }
    buff = 0;
    return nleft;
}

But everytime I try to pass data from client and server, I always get special characters (dirty memory), this is what I tried to do:

  • I have done a memset() before the FullWrite
  • Tried with a fflush(stdin), even if I know its not a good practice
  • Tried removing buff = 0 at the end of my functions

This is what I do to call two consecutive FullRead and FullWrites.

This is on the server:

FullRead(connfd, buff, strlen(buff));
printf("Buff: %s\n", buff);
FullRead(connfd, buff, strlen(buff));
printf("Buff: %s", buff);

And this is on the client:

memset((void *)buff, 0, sizeof(char)*1000);
scanf("%s", buff);
fflush(stdin);
FullWrite(sockfd, buff, strlen(buff));

memset((void *)buff, 0, sizeof(char)*1000);
scanf("%s", buff);
fflush(stdin);
FullWrite(sockfd, buff, strlen(buff));

If I write on my linux terminal something like "001" from the server, on the client I see "001�t" or similar things.. things like that. Can't come out from this situation.


I tried changing my code removing buff = 0 from FullWrite() and FullRead(), removed the fflush() and the memset, calling the functions like this:

Client

scanf("%s", buff);
FullWrite(sockfd, buff, sizeof(buff));

Server

length = FullRead(connfd, buff, strlen(buff));
printf("Buffer: %.*s\n", length, buff);

Still the server reads and prints junk.


Solution

  • Two problems:

    • you are passing strlen(buff) to FullRead() - you probably want sizeof(buff) (hard to tell without seeing how you declare/initialise this buffer).

    • you are not terminating the string returned from FullRead() - you need a '\0' immediately after the received data otherwise the subsequent printf() will most likely emit garbage characters beyond the end of the string.

    Also, as you already know, you should not be calling fflush(stdin).