-2

So, my problem is pretty simple, I don't know why the first segment of code does not work properly. The program read a string of 12 characters from a pipe and the strcat fuction moves the pointer of buff from the first character to the next every time the fuction is executed and so after a few interactions the read function make the program fail because the buffer is not big enough anymore. Using the sprintf function and another string solve the issue but i don't understand what cause the problem. Thanks for the help.

int n; 
char buff[15];
close(fd[1]);
    while(n = read(fd[0],buff,12) > 0){      
        strcat(buff,"\n");
        write(1,buff,13); 
        buff[0] = '\0'; 
        }
int n; 
char buff[15];
char output[15];
close(fd[1]);
while(n = read(fd[0],buff,12) > 0){      
            sprintf(output,"%s\n",buff); 
            write(1,output,13); 
            buff[0] = '\0';       
        }

2 Answers2

1

The proper code terminates the buffer, which is assumed to contain a string read:

int n;
char buff[15];
close(fd[1]);
while((n = read(fd[0],buff,12)) > 0){
    buff[n] = '\0'; /* add terminating null-character */
    strcat(buff,"\n");
    write(1,buff,n+1);
}

and

int n;
char buff[15];
char output[15];
close(fd[1]);
while((n = read(fd[0],buff,12)) > 0){
    buff[n] = '\0'; /* add terminating null-character */
    sprintf(output,"%s\n",buff);
    write(1,output,n+1);
}
  • Note the extra ( and ) in the assignment to n
  • Note the use of n, the actual number of characters read
  • And note, as Mike said, the termination of the string.
Paul Ogilvie
  • 25,048
  • 4
  • 23
  • 41
-1

strcat and %s specifier of sprintf expects strings, which means "null-terminted sequence of characters" in C.

If the contents from the pipe is not guaranteed to null-terminated, you have to add terminating null-character.

int n;
char buff[15];
close(fd[1]);
while(n = read(fd[0],buff,12) > 0){
    buff[12] = '\0'; /* add terminating null-character */
    strcat(buff,"\n");
    write(1,buff,13);
    buff[0] = '\0';
}
int n;
char buff[15];
char output[15];
close(fd[1]);
while(n = read(fd[0],buff,12) > 0){
    buff[12] = '\0'; /* add terminating null-character */
    sprintf(output,"%s\n",buff);
    write(1,output,13);
    buff[0] = '\0';
}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70