0
#include<stdio.h>
#include<unistd.h>
char *msg1="HELLLO",*msg2="NONONO";//global declaration prints without any garbage value
int main()
{
/*char *msg1="HELLLO",*msg2="NONONO";"global declaration prints with garbage value */
char buf[6];
int file[2],i;
if(pipe(file) < 0)
    printf("\nyou are out");
write(file[1],msg1,6);
write(file[1],msg2,6);
for(i=1;i<=2;i++){
    read(file[0],buf,6);
    printf("\n%s",buf);}
return 0;

}

Output: As Global Variable: HELLLO NONONO

As local variable: HELLLO▒▒▒ NONONO▒▒▒

jeff rius
  • 3
  • 3
  • 4
    `char buf[6]; read(file[0],buf,6);` -- there is no room in the buffer for the terminating `NUL` character. https://en.wikipedia.org/wiki/C_string_handling – axiac Apr 11 '18 at 11:36
  • 1
    *And* you don't null terminate either. `read(2)` doesn't null-terminate. – P.P Apr 11 '18 at 11:40
  • Also read this question: https://stackoverflow.com/questions/4418708/whats-the-rationale-for-null-terminated-strings – axiac Apr 11 '18 at 11:40
  • file[2] supposed to be uninitialized? this is cool – purec Apr 11 '18 at 11:46

0 Answers0