0

So while I was learning pipes programming in C, I decided to comment out the opening pipe() code and see what happens, and the result certainly isn't what I expected.

Here's the code

#include <stdio.h>
#include <unistd.h>

#define MSGSIZE 16

char *msg1 = "Hello, World #1";
char *msg2 = "Hello, World #2";
char *msg3 = "Hello, World #3";

int main(void) {
    char inbuf[MSGSIZE];
    int p[2], j;

    /* if (pipe(p) == -1) { */
    /*  perror("pipe call"); */
    /*  exit(0); */
    /* } */

    write(p[1], msg1, MSGSIZE);
    write(p[1], msg2, MSGSIZE);
    write(p[1], msg3, MSGSIZE);

    for (j = 0; j < 3; j++) {
        read(p[0], inbuf, MSGSIZE);
        printf("%s\n", inbuf);
    }

    exit(0);
}

And here's the output of the program:

Hello, World #1Hello, World #2Hello, World #3^C

In the Emacs shell the output is even more peculiar

Hello, World #1^@Hello, World #2^@Hello, World #3^@

So I understand 0 and 1 are file descriptors for stdin and stdout respectively, but I just write() to the second element of an int array and read() from the first element, how did I end up with this output?

Thanks in advance to anyone who takes out his/her time to explain this!

HarryGeez
  • 63
  • 1
  • 1
  • 7
  • 4
    You are wasting your time. Accessing uninitialised variables is Undefined Behaviour. By definition that means any behaviour can occur and it is pointless trying to explain it. Just don't do it. See [Does “Undefined Behavior” really permit *anything* to happen?](http://stackoverflow.com/questions/32132574/does-undefined-behavior-really-permit-anything-to-happen) – kaylum Oct 08 '16 at 06:05
  • i don't see any undefined behaviour, p might have an undefined value, but read and write have defined behaviour for any integer given as a file descriptor. – Secto Kia Oct 08 '16 at 07:18

0 Answers0