Segmentation Fault at scanf statement

here is the question https://www.hackerrank.com/challenges/weighted-uniform-string/problem?isFullScreen=true

 #include <assert.h>

    #include <limits.h>

    #include <math.h>

    #include <stdbool.h>

    #include <stddef.h>

    #include <stdint.h>

    #include <stdio.h>

    #include <stdlib.h>

    #include <string.h>

        int main(){
            
            long int i,j,n,flag=0,sum=0;
        char str[10000001];
        char ch;

        long int arr[100000000];
        long int arr1[100000000];


        scanf("%s",str); //showing segmentation fault here in hackerrank ide but working on codechef ide
        scanf("%ld",&n);

        for(i=0;i<n;i++){
        scanf("%ld",&arr1[i]);
        }

        for(i=0;i<strlen(str);i++){
        ch=str[i];
        if(i==0){

            if(str[i]==str[i+1]){
        sum=sum+(ch-96);
        arr[i]=sum;
            }else{
        sum=sum+(ch-96);
        arr[i]=sum;

        sum=0;
            }
        continue;
        }
        if(str[i]==str[i+1]){
        sum=sum+(ch-96);
        arr[i]=sum;
        }else{
            sum=sum+(ch-96);
            arr[i]=sum;
            sum=0;
        }

        }


        for(i=0;i<n;i++){
            flag=0;
           for(j=0;j<strlen(str);j++){
              
              if(arr1[i]==arr[j]){
                  flag=1;
                  break;
              } 
              
           } 
            (flag==1)?printf("YES\n"):printf("NO\n");
        }

        return 0;
        }

Please give the full code (this won’t compile as it’s missing some headers).

What is the test input it’s crashing on?

1 Like

i have included header files. It is showing segmentation fault at scanf statement and only in hackerrank ide but not in codechef

My C isn’t very good, but I can’t see anything particularly wrong with the code. Looks like it might be a stackoverflow due to the huge arrays you’re declaring, and in fact shortening each of them to 100'000 each allows the testcase:

hello 5 10 10 10 10 10

to run without crashing.

How big do these arrays actually need to be? Can you link to the problem statement?

Edit:

Thanks for adding the headers, but can you please format them, too? XD

1 Like

those arrays are working fine in codechef ide…But i have to submit the code in hackerrank… I have included the link to the question. Please help!!

Thanks. Please reduce the size of arrays str, arr and arr1 to 100001 or so and try again.

2 Likes

@manoj_rawat in c you can’t intialize array of size more than 10^6.you are intializing array of 10^8 which causes segmentation fault. just initialize array of 10^6 size.

1 Like