简体   繁体   中英

why i am getting segmentation fault only when run my code in codechef?

This here is the code. The code works fine when i run it in VS Code 2019 and other online compilers as well! But when run it in Codechef here i get some runtime segmentation fault error.

The code

#include<stdio.h>
int main(void)
{
    int T;
    scanf("%d", &T);
    while (T >= 1 && T <= 100)
    {
        char a[10] ;
        int x_counter = 0, y_counter = 0;
        scanf("%s", &a);
        char* ptr = a;
        while (*ptr != '\0')
        {
            if (*ptr == 'x')
                x_counter++;
            else if (*ptr == 'y')
                y_counter++;
            ptr++;
        }
        if (x_counter < y_counter)
        {
            printf("%d\n", x_counter);
        }
        else if (y_counter <= x_counter)
        {
            printf("%d\n", y_counter);
        }
        T--;
    }
    return 0;
}

you program will run into undefined behavior UB cos you conversion specifier in the scanf "%s" expects a char* but you are passing array of char pointers ( char** or char(*)[] ).hence the pointer arguments for scanf must be of a type that is appropriate for the value returned by the corresponding conversion specification!! I recommend you to limit the scanf function and flush the stdin buffer in each iteration see below:

int c;
scanf("%9s", a);
while ((c = fgetc(stdin)) != '\n' && c != EOF); /* Flush stdin */

since scanf return EOF if the end of input is reached before either the first successful conversion or a matching failure occurs. EOF is also returned if a read error occurs, the error indicator for the stream is set, and errno is set to indicate the error. errno is an integer variable definded in <errno.h> header, which is set by system calls and some library functions in the event of an error to indicate what went wrongwe can add the layer below:

#include <errno.h>
#include <string.h>
....
if(scanf("%9s", a) == EOF)
{
    puts(strerror(errno));
    exit(EXIT_FAILURE);
}
char *strerror(int errnum);

The strerror() function returns a pointer to a string that describes the error code passed in the argument errnum

for further details regarding strerror and errno . go to the links below: errno strerror

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM