Tony Ng Wei Shyang
Tony Ng Wei Shyang

Reputation: 485

Run-Time Check Failure #2 - s (C language on Microsoft Visual C++ 2015 (community version))

I have faced this problem : Run-Time Check Failure #2 - S in visual studio 15 . This happen before where I also trying to use array in C language. According to my textbook, what happen to the below code is

char myname[20];

printf("Type your name:");
scanf("%19s", myname);

printf("\n\n%s,Welcome to the class\n", myname);

According to the textbook, if I input my name as for example : Tony Stark, the problem will only scan the Tony and ignore all the thing after the blank space. However, when I try it, it appear Run-Time Check Failure #2.

Also in below code

#include<stdio.h>

int main(void)
{
    char name[30];
    int seat[30] = { 0 };
    int i, seatt, j;
    char decision[1];

    do
    {
        printf("Hi, what is your name? ");
        scanf("%s", name);

        printf("Welcome %s!\n\n", name);

        printf("*********************\n");
        printf("CINEMA 1 SEATING PLAN\n");
        printf("*********************");
        for ( i = 0; i < 30; i++)
        {
            if (i % 5 == 0)
            {
                printf("\n\n");
            }
            if (seat[i] == 0)
            {
                printf("%3d", i);
            }
            else
            {
                printf("%3s", "**");
            }
        }
        printf("\n\n*********************");
        do
        {
            printf("\n\nWhich seat do you want? ");
            scanf("%d", &seatt);
            if (seat[seatt]!=0)
            {
                printf("Sorry, seat is taken!\n");
                for ( j = 0; j < 30; j++)
                {
                    if (seat[j] == 0)
                    {
                        printf("Suggest to take seat: %d", j);
                        break;
                    }
                }
            }
        } while (seat[seatt] != 0);
        ++seat[seatt];

        printf("\n\nWould you like to make next booking (Y or N)? ");
        scanf("%s", decision);
        printf("\n\n");
        if (decision[0] == 'Y' || decision[0] == 'y')
        {
            system("cls");
        }

    } while (decision[0] == 'Y' || decision[0] == 'y');
    printf("See you again!\n");

    return 0;
}

Everything is ok, until when until the last part where it ask me where to book the next ticket, if I keyin another other than Y, it also appear the same problem.

Upvotes: 0

Views: 359

Answers (1)

Thomas B Preusser
Thomas B Preusser

Reputation: 1189

You are not very careful with respect to stack overflows. In the second code, you use:

char decision[1];
scanf("%s", decision);

The scanf will append a trailing \0 termination character already interfering with some other data on the stack even if you really only input a single character. More disaster is at hand when the user input is longer. Scan with a "%c" format in this case.

Upvotes: 3

Related Questions