Search code examples
carraysgets

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?


Solution

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