Search code examples
cgets

Why is first gets() input is lost in this c program?


In the following simple code the input of the first gets is not showing up. Any help please?

int main()
{
    int x;
    char tmp[1];
    char anystr[10], srchstr[1];

    printf("Enter an string : ");
    gets(anystr);

    printf("Enter any character you want to search in input string: ");
    gets(srchstr);

    printf("anystr : %s\n",anystr);
    printf("anystr : %c\n",anystr[0]);
    printf("srchstr : %c\n",srchstr[0]);

    return 0;
}

The Output is null for first fgets string anystr:

Enter an string : hello
Enter any character you want to search in input string: h
anystr : 
anystr : 
srchstr : h

Solution

  • You have a problem because you have undefined behaviour.
    The UB is caused by having second gets() write beyond the 1-char array srchstr. What is written beyond is the terminator '\0'.
    See the gets() docu: http://en.cppreference.com/w/c/io/gets

    No answer to this question should omit to mention (using Jonathan Lefflers nice link):
    Why is the gets function so dangerous that it should not be used?

    That is it. UB and dangerous. Done. End of answer.

    Well....
    One speculation of which specific nasal demon is flying around would be:
    strchr is located right before anystr. This means that the one beyond access hits right the first char inside anystr.
    I.e. it terminates that other string right after zero characters.
    I.e. it makes it empty.
    Printing it therefor has no output, even though the second character is still from the perviously written string.