Jesse Cai Jesse Cai - 1 year ago 101
C Question

uninitialized array passed into pipe(2)

I was looking at how to use pipe(2) on the man pages, and I don't understand a line in the source code they provided.

main(int argc, char *argv[])
int pipefd[2]; //Isn't this undefined??? so pipe(pipefd) would throw an error?
pid_t cpid;
char buf;

if (argc != 2) {
fprintf(stderr, "Usage: %s <string>\n", argv[0]);

if (pipe(pipefd) == -1) {

cpid = fork();
if (cpid == -1) {

if (cpid == 0) { /* Child reads from pipe */
close(pipefd[1]); /* Close unused write end */

while (read(pipefd[0], &buf, 1) > 0)
write(STDOUT_FILENO, &buf, 1);

write(STDOUT_FILENO, "\n", 1);

} else { /* Parent writes argv[1] to pipe */
close(pipefd[0]); /* Close unused read end */
write(pipefd[1], argv[1], strlen(argv[1]));
close(pipefd[1]); /* Reader will see EOF */
wait(NULL); /* Wait for child */

I thought non-static function variables are just whatever is in memory? Why does this source code work?

Answer Source

pipefd array serves as output argument here, so there is no need to initialize it. pipe function writes into it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download