简体   繁体   中英

Does the gets() function in C automatically add a NULL character at the end of the input string?

I am writing a simple program to convert a number(+ve,32-bit) from binary to decimal. Here's my code:

int main()
{
    int n=0,i=0;
    char binary[33];
    gets(binary);
    for (i = 0; i < 33, binary[i] != '\0'; i++)
        n=n*2+binary[i]-'0';
    printf("%d",n);
}

If I remove binary[i]!='\\0' , then it gives wrong answer due to garbage values but if I don't it gives the correct answer. My question is: does the gets function automatically add a '\\0' (NULL) character at the end of the string or is this just a coincidence?

Yes it does, writing past the end of binary[33] if it needs to.

Never use gets ; automatic buffer overrun.

See Why is the gets function so dangerous that it should not be used? for details.

When gets was last supported (though deprecated) by the C standard, it had the following description (§ 7.19.7.7, The gets function):

The gets function reads characters from the input stream pointed to by stdin , into the array pointed to by s , until end-of-file is encountered or a new-line character is read. Any new-line character is discarded, and a null character is written immediately after the last character read into the array.

This means that if the string read from stdin was exactly as long as, or longer than, the array pointed to by s , gets would still (try to) append the null character to the end of the string.

Even if you are on a compiler or C standard revision that supports gets , don't use it. fgets is much safer since it requires the size of the buffer being written to as a parameter, and will not write past its end. Another difference is that it will leave the newline in the buffer, unlike gets did.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM