Search code examples
cstringstrcat

Why the strcat function move the pointer to the next character?


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';       
        }

Solution

  • 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.