Search code examples
cvisual-studiouser-inputgets

gets() function throw exception?


void getInputWith_gets()
{
    char firstName[5];
    char lastName[5];
    printf("Enter your first name: ");
    gets(firstName);
    printf("Enter your last name: ");
    gets(lastName);
    printf("Hello, %s, %s\n", firstName, lastName);
}

int main(int argc, char **argv)
{
    getInputWith_gets();
    //getInputWith_fgets();
    system("pause");
    return 0;
}

I am using MS Visual Studio 2017, I know the restriction of using the "gets()" function that I have a maximum of 5 chars to be entered but if I entered exactly 5 characters, the console prints correctly(and doesn't print "press any key to continue... due to "system("pause") statment") but the program get stuck at the debugger screen and after the last "printf" statement I get a a red error symbol with a pop-up saying: "Run-Time Check Failure #2 - Stack around the variable 'lastName' was corrupted." does this means that the "gets()" function will read 5 exclusive characters only?


Solution

  • You have multiple bugs here:

    Also note that the function format void getInputWith_gets() is obsolete style, you should be writing void getInputWith_gets(void).

    Overall, it seems you are learning C from a completely outdated source (over 20 years outdated).