Vibha Sharma
Vibha Sharma

Reputation: 23

Does a copied string end with a '\0' (Section 1.9 The C Programming Language K&R2)

In the last line of copy function I have stored a '\0' at the end of the copied string, this was not originally in the code.

include <stdio.h>
#define MAXLINE 1000               /* maximum input line size */

int getline(char line[ ], int maxline);    
void copy(char to[ ], char from[ ]);

/* print longest input line*/
int main()
{
    int len;                   /* current line length */
    int max;                  /* maximum length seen so far */
    char line[MAXLINE];      /*current input line*/
    char longest[MAXLINE];  /* longest line saved here */

    max=0;
    while ((len=getline(line, MAXLINE)) > 0)     
        if (len > max)
        {
            max=len;
            copy(longest, line); 
        }
    if (max>0)         /* there was a line*/
        printf("%s", longest);
    return 0;
}

/* getline: read a line into s, return length */
int getline(char s[ ], int lim)
{            
    int c,i;
    for(i=0; i<lim-1 && (c=getchar())!=EOF && c!='\n'; ++i)
        s[i]=c;
    if(c=='\n')
    {
        s[i]=c;
        ++i;
    }
   s[i]='\0';
   return i;
}

/* copy: copy 'from' into 'to'; assume to is big enough */
void copy(char to[], char from[])
{
    int i;
    i=0;
    while((to[i]=from[i])!='\0')
        ++i;
    to[i] = '\0';      /*<-----Problematic Area*/
}

My question here is, whether the copied string already contains a '\0' at the end. If it is not so then is it a good practice to include it as I have done in the code.

Upvotes: 2

Views: 77

Answers (1)

The statement

while ((to[i] = from[i]) != '\0')
    ++i;

first assigns the value of from[i] to to[i] and then compares the assigned value to \0 - if it was the null terminator that was just copied, the loop ends.

Thus

to[i] = '\0';

is unnecessary, but not otherwise incorrect here.

However, having unnecessary code around is not good style because it makes refactoring and reasoning about the other code harder. Just the presence of that last assignment could then confuse a future reader into thinking that the loop in itself is not sufficient to properly terminate the string.

Additionally, should someone come and edit the code into

while ((*to++ = *from++));

as suggested by WhozCraig, they could then mistakenly think that they do need to add the null terminator, this time potentially writing out of bounds:

*to++ = 0;

Upvotes: 5

Related Questions