Why is putchar() writing a new line in this simple code?

115 views Asked by At

I do not understand why excessive white space is being written to stdout when I run this program.

int main(int argc, char **argv)
{
    argv++;

    for (int i = 0; i < argc - 1; i++)
    {
        for (int j = 0; j < strlen(*argv); j++)
        {
            putchar(*(*(argv + i) + j));
        }
        printf("\n");
    }
    
}

Output:

(base) benjamin@benjamin-G5-5587:~$ ./uecho hello world baby yoyoyo                           
hello                                                                                         
world                                                                                         
baby                                                                                          
         //whitespace?                                                                                     
yoyoy  
1

There are 1 answers

4
ShadowRanger On BEST ANSWER

Your inner loop condition is wrong, causing you to read out of bounds. It's always limited by strlen(*argv), the first argument (thanks to the earlier argv++), even when processing the second and subsequent arguments. Since you read out to the length of "hello", you overread "baby", and fail to read all of "yoyoyo". Overreading baby by one character ends up writing a NUL to stdout, which I'm guessing your terminal is interpreting in a manner similar to a newline.

I'd suggest:

  1. Fixing the problem so you use the length of each argument to print it, and
  2. Replacing hard to understand pointer arithmetic with simple array indexing syntax

End result would look like:

int main(int argc, char **argv)
{
    for (int i = 1; i < argc; i++)  // Adjust bounds to loop over provided args without mucking with argv directly
    {
        for (int j = 0; j < strlen(argv[i]); j++)  // Loop to length of current arg
        {
            putchar(argv[i][j]);
        }
        printf("\n");
    }
}