Arnav Bhattacharya
Arnav Bhattacharya

Reputation: 25

What is the specific reason for the runtime error I'm getting here?

#include<stdio.h>
#include<string.h>
void main()
{
    char a,b,c;
    printf("Enter alien names:\n");
    scanf("%s\n%s\n%s\n",a,b,c);
    printf("The alien names are %s, %s and %s. A meteor hit %s's spaceship. A star scratched %s\'s spaceship. But %s fixed %s and %s\'s spaceships. The three became friends and are from the planet BYG (which means BLUE YELLOW GREEN)",a,b,c,a,b,c,a,b);
}

What is the specific reason for the runtime error I'm getting here?

Upvotes: 0

Views: 106

Answers (5)

ad absurdum
ad absurdum

Reputation: 21325

The posted code has undefined behavior, because the variables a, b, and c are of type char, while the %s conversion specifier in the call to scanf() is expecting a pointer to the first element of a character array that can hold the input string. Mismatched conversion specifers and arguments in a scanf() call lead to undefined behavior, and attempting to write too many characters into the receiving array causes undefined behavior.

The first problem can be fixed by declaring a, b, and c as arrays large enough to hold expected input:

char a[100], b[100], c[100];
...
scanf("%s\n%s\n%s\n", a, b, c);

Note that arrays decay to pointers to their first elements in most expressions, including function calls, so here a is a pointer to the first element of the character array a[]; this is equivalent to &a[0].

There is still a possibility for undefined behavior if the user enters too many characters. To avoid this, always specify a maximum width when using scanf() to read user input into a string. Note here that the specified width is the maximum number of characters that will be read for that input item, not including the null terminator, \0, which will be automatically added by scanf(), so the maximum width must be at least one less than the size of the receiving array:

scanf("%99s\n%99s\n%99s\n", a, b, c);

But if you compile and run this code, you will find that it does not behave as expected. After the third name is entered, the program will continue waiting for more input. This is because the \n character is a whitespace character, and when scanf() encounters a whitespace character in a format string, it reads and discards zero or more whitespace characters in the input until a nonwhitespace character is encountered, or until no more characters can be read. The %s directive tells scanf() to read characters until a whitespace character is encountered. So when the user presses Enter after the final name, scanf() completes matching input characters for the final name and returns the \n character to the input stream; then the \n is reached in the above format string, and scanf() matches the aforementioned \n character in the input stream, and any further whitespace characters that are encountered. This will end if the user enters another nonwhitespace character, or signals end-of-file from the keyboard (e.g., with Ctrl-D or Ctrl-Z).

To avoid this complication, remember that it is almost never correct to end a scanf() format string with a whitespace character. Also, there is no need to use \n rather than a space character, since both are simply interpreted as whitespace directives by scanf():

scanf("%99s %99s %99s", a, b, c);

It would further improve the posted code if the return value from the call to scanf() were checked before attempting to use the input. Since scanf() returns the number of successful assignments made, this value should be 3:

#include <stdio.h>
#include <string.h>

int main(void)
{
    char a[100], b[100], c[100];

    printf("Enter alien names:\n");
    int ret_val = scanf("%99s %99s %99s", a, b, c);

    if (ret_val == 3) {
        printf("The alien names are %s, %s and %s. A meteor hit %s's "
               "spaceship. A star scratched %s\'s spaceship. But %s "
               "fixed %s and %s\'s spaceships. The three became friends "
               "and are from the planet BYG (which means BLUE YELLOW GREEN)\n",
               a, b, c, a, b, c, a, b);
    } else {
        puts("Input error");
    }
}

Upvotes: 1

John Bode
John Bode

Reputation: 123468

The specific reason for the runtime error is this line:

scanf("%s\n%s\n%s\n",a,b,c);

The %s conversion specifier tells scanf to read a sequence of non-whitespace characters from the input stream (skipping over leading whitespace) and store that sequence to an array of char pointed to by the corresponding argument. The problem is that a, b, and c are not pointers to char; they're single char objects that haven't been initialized. The odds of any of them containing a value that corresponds to an address that scanf can write to is almost non-existant.

First, change the declarations of a, b, and c to

char a[SOME_LENGTH] = {0}; // initialize array contents to 01
char b[SOME_LENGTH] = {0};
char c[SOME_LENGTH] = {0};
where SOME_LENGTH is a number that's long enough to contain the longest string you expect to enter plus one extra space for the string terminator. IOW, if the longest string you intend to read is 10 characters long, then your declarations need to be

char a[11] = {0};
char b[11] = {0};
char c[11] = {0};

Secondly, change your scanf call to

scanf( "%(SOME_LENGTH-1)s %(SOME_LENGTH-1)s %(SOME_LENGTH-1)s", a, b, c );

where (SOME_LENGTH-1) is the length of your buffer minus 1. Again, assuming SOME_LENGTH is 11:

scanf( "%10s %10s %10s", a, b, c );

This will help prevent a buffer overrun in the event you enter a string longer than what the buffer is sized to hold.

Both the %s conversion specifier and a blank space in the format string tell scanf to consume and discard any leading whitespace. You can run into trouble specifying whitespace characters in the format string.

Additional notes:

main returns int, not void - change your main to

int main (void)
{
  ...
}


  1. If there are fewer elements in the initializer than there are in the array, then excess elements are initialized to 0. So in this case, the first element is *explicitly* initialized to 0, and the remaining elements are *implicitly* initialized to 0.

Upvotes: 0

Bicolano
Bicolano

Reputation: 90

    //There are things that shoudn't be there. Im not a pro but this is what I think.

    #include<stdio.h>
    #include<string.h>//you have include this library but you didn't use a function from it.
                      //I think what you want to do is use the str functions like strcpy
                      //but in this case you don't need to use it.

    void main()
    {
        char a[25],b[25],c[25];//Here you declared a character a, b and c. But if you want to store a string, you have to declare an array of characters. So instead of a, b, c, it's a[someValue], b[someValue] and c[someValue].
                   //Declare an array with a size that you think will cover the whole "alien name". e.g. a[25]..
                   //but i don't know, maybe you did it on purpose. Maybe you just want to name the aliens with one character like A, B, C. But if you want to name the aliens with a long name, you must declare an array.


        printf("Enter alien names:\n");
        scanf("%s\n%s\n%s\n",a,b,c);//You don't need to put the "\n" between those "%s". "\n" means "newline". It will work without it because scanf automatically reads next set of characters when it meets white space of newline.
                                    //--so you can remove "\n" in there and replace it with space. But you can leave it there also but  you really have to remove the last "\n" because scanf will search again for the next 
                                    //--new line before it will end asking for input and pressing enter will not work because you have to type another set of characters before scanf will read the last "\n" that you put at scanF. 
                                    //Another mistake here is the format specifier that you used (%s). It doesn't match declaration because you declare char a, b, c, that will only store one character each.
                                    //In case that you're really just storing one character each alien's name, you have to use the "%c" instead of "%s" and you must pass the reference of the char variable in 
                                    //--scanf, e.g. scanf("%c %c %c", &a, &b, &c);
                                    //Just remember that if you plan on storing a string or a long name there, you must declare an array like I said at the beginning.
                                    //--and if it's an array, you don't need to include the '&' on every variable when you're passing it in scanF.


        //There's nothing wrong here if you're alien's names are string. 
        printf("The alien names are %s, %s and %s. A meteor hit %s's spaceship. A star scratched %s\'s spaceship. But %s fixed %s and %s\'s spaceships. The three became friends and are from the planet BYG (which means BLUE YELLOW GREEN)",a,b,c,a,b,c,a,b);
    }

Upvotes: 0

Weather Vane
Weather Vane

Reputation: 34585

What is the specific reason for the runtime error I'm getting here?

The function scanf using the format specifier %s expects to be passed the address of a char array, in which to place the input data. For example an array such as

char a[100];

However, you pass simple char variables a and b and c which can hold values in the range -128 to 127, or 0 to 255, depending on whether the implementation's char is signed or unsigned.

These variables were not even initialised, so indeterminate values were passed to scanf. But even if they had been initialised, it is very likely that the values passed will cause a segfault, when used as addresses.

My compiler issued 2 warnings for each of a, b and c passed to scanf.

warning C4477: 'scanf' : format string '%s' requires an argument of type 'char *', but variadic argument 1 has type 'int'

warning C4700: uninitialized local variable 'a' used

Please enable and act on all compiler warnings.

Upvotes: 0

Iliya Iliev
Iliya Iliev

Reputation: 151

To solve this issue you should simply consider to use strings (arrays of chars) to contain the different names.

Here is an example how to do that:

    void main()
{
// The string "a" can contain up to 100 symbols (chars).
char a[100];

printf("Enter an alien name:\n");

scanf("%s",a);

printf("The alien name is %s.", a);

}

The difference between "char a" and "char a[100]" is that in the first case the variable "a" corresponds to a single character and in the second it corresponds to a string - an array of chars which can contain up to 100 characters.

Upvotes: 1

Related Questions