'Would you please explain why I am getting error in this testcase 99? [closed]

https://codeforces.com/contest/61/problem/A Here in the testcase 99 of this I am experiencing an error which I am not getting in codeblocks. What I have identified is, after printing the needed output correctly, some 1s are being printed. I am not getting the fact why these 1s are being printed.

Here is my code:

#include<stdio.h>
#include<string.h>
int main()
{
    char x[100],y[100];
    scanf("%s%s",&x,&y);
    for(int i=0;i<strlen(x);i++)
    {
        if(x[i]==y[i])
        {
            printf("0");
        }
        else
        {
            printf("1");
        }
    }
    return 0;
}

Image: Error in testcase 99

c


Solution 1:[1]

That use of scanf is dangerous. It can lead to a buffer-overflow, that will produce undefined behaviour (behaviour may be different on different platforms, or even each time that you run the program).

Turn on compiler warnings. Use a good static analysis tool, or better use a safer language such as golang. Then use scanf format strings that prevent buffer overrun. On gcc the option -Wall will turn on this warning. You may also want to turn on some other warnings, or turn up the level to be more strict (especially for new code).

Solution 2:[2]

You have some issues in your code:

    char x[100],y[100];
    scanf("%s%s",&x,&y);

The type of second and third argument for scanf is not correct. They may have correct value, but strictly speaking they are wrong. You need a char* but you provide a char (*)[]. You should just use x,y without the &.

Also you do not take care about potential buffer overflows.

To avoid buffer overflows, you should add a length limit to your format specifier. It must be one less than the size of your arrays.

Also you are required to deal with numbers up to 100 digits. That does not fit into your buffers. If you need to handle strings of length 100, your arrays must have size 101.

You don't do this. If you get a string that is too long for one of your arrays, you will probably overflow into the next buffer losing the terminator byte.

That said, the 2 lines above should look like this:

    char x[101],y[101];
    scanf("%100s%100s", x, y);

Additionally you should always check return value of scanf and other IO functions.

To improve performance a bit, you should also not call strlen in each iteration of the loop. Instead you should call it once before the loop and store the value to use it in the loop condition.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Gerhardh