Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random characters when reading from pipe

In the following code :

    ...
    char *message = "This is the message!";
    ...

    printf("Writing to file descriptor FD[%i] \n", fd[1]);
    write( fd[1], message, strlen(message));
    printf("Reading from file descriptor FD[%i] \n", fd[0]);
    read( fd[0], buffer, strlen(message));
    printf("Message from FD[%i] : \"%s\" .\n", fd[0], buffer);

I get the following output :

 "This is the message!���" .

But if I remove the "!" from my message, the output doesn't have random characters... Any idea why I get these 3 random characters to appear?

like image 839
Erwald Avatar asked Jan 02 '13 01:01

Erwald


1 Answers

When you write your message of length strlen(whatever), that does not include the terminating NUL character. Hence what comes out at the other end is not a C string but rather just a collection of characters.

What follows that collection of characters in memory depends entirely upon what was there before you read them from the pipe. Since it's not a C string (except by possible accident if the memory location following just happened to already contain a NUL), you should not be passing it to printf with an unbounded %s format specifier.

You have two possibilities here. The first is to send the NUL character along with the data with something like:

write (fd[1], message, strlen(message) + 1);

or (probably better) use the return value from read which tells you how many bytes were read, something like:

int sz = read (fd[0], buffer, sizeof(buffer));
// should probably check sz here as well.
printf ("Message from FD[%i] : \"%*s\" .\n", fd[0], sz, buffer);
like image 193
paxdiablo Avatar answered Oct 20 '22 00:10

paxdiablo