Chef and the feedback: Run-time error


    #include<stdio.h>
    #include<string.h>
    #include<stdlib.h>
    
    //to search for any of the two sub-strings "010" or "101" in a string given by user.
    
    int main(){
    
    	char good1[]= "010";
    	char good2[]= "101";
    	char *ret1;
    	char *ret2;
    	int t;
    
    	scanf("%d", &t);      //no. of testcases
    
    	while(t--){
    		char str[10000];
    
    		scanf("%s", str);
    
            ret1= strstr(str, good1);
            ret2= strstr(str, good2);
    
            if(ret1 != NULL || ret2 != NULL ){
                printf("Good\n");
            }
            else
                printf("Bad\n");
    	}
    	return 0;
    }
    
    
I am getting a run-time error(SIGSEGV) and I can't seem to understand where I went wrong. I have seen others' codes as well, and my declarations and everything is also okay, but still the code is not working.

it says in the constraint that 1 ≤ |S| ≤ 10^5. But you’ve taken a string length of 10^4. change str[10000] to str[100000]

1 Like

Increase the character array limit.

Check the below version of your code:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
//to search for any of the two sub-strings "010" or "101" in a string given by user.

int main(){

char good1[]= "010";
char good2[]= "101";
char *ret1;
char *ret2;
int t;

scanf("%d", &t);      //no. of testcases

while(t--){
    char str[1000005];  // <<<<< Here, earlier you declared the size to be 10^4. However, the problem constraint says 10^5 to be the limit.

    scanf("%s", str);

    ret1= strstr(str, good1);
    ret2= strstr(str, good2);

    if(ret1 != NULL || ret2 != NULL ){
        printf("Good\n");
    }
    else
        printf("Bad\n");
}
return 0;
}

Pro tip: Whenever you get such run time errors - almost always it is because of invalid memory accesses. So whenever you get such errors, directly go and check your array limits and check if there is any chance that your code could go beyond the limit of current array size.

4 Likes

The size of the char array should be kept at least 1 greater the maximum size of the string to allow for the terminating null character.

3 Likes