cif-statementc-stringsstrstrnull-pointer

how to fix a Runtime error in a char array


I am currently working on a program and have run into a runtime error, ironically I cannot seem ti find the source of it at all, I have tried playing around with the char[] size, but since the problem's condition specifies the limit should be 10^5 there is not much I can do there.

Here is the code:

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


int main() {

char stations[100003], seq1[103], seq2[103];
int f = 0, b = 0, a = 0;
scanf("%s", stations);
scanf("%s", seq1);
scanf("%s", seq2);

if (strlen(stations) < strlen(seq1) + strlen(seq2))
printf("fantasy");
else {
if (strstr(strstr(stations, seq1), seq2) != 0) {
  f = 1;
}
if (strstr(strstr(strrev(stations), seq1), seq2) != 0) {
  b = 1;
}
if (f == 1 && b == 1) {
  a = 1;
}

if (a == 1)
  printf("both");
else if (f == 1)
  printf("forward");
else if (b == 1)
  printf("backward");
else
  printf("fantasy");
}
return 0;
}

and here is the compiler output:

 exit code: -1073741819 (STATUS_ACCESS_VIOLATION), checker exit code: 0, verdict: RUNTIME_ERROR

Any help is very much appreciated!


Solution

  • These if statements

    if (strstr(strstr(stations, seq1), seq2) != 0) {
      f = 1;
    }
    if (strstr(strstr(strrev(stations), seq1), seq2) != 0) {
      b = 1;
    }
    

    are unsafe. The function strstr can return a null pointer. In this case the outer call of strstr invokes undefined behavior because a null pointer is passed as an argument.

    You need to write something like

    const char *p;
    
    if ( ( p = strstr(stations, seq1) ) && strstr( p, seq2) ) {
      f = 1;
    }
    if ( ( p = strstr(strrev(stations), seq1) ) && strstr( p, seq2) )  {
      b = 1;
    }
    

    Or like

    const char *p;
    
    if ( ( p = strstr(stations, seq1) ) && strstr( p + strlen( seq1 ), seq2) ) {
      f = 1;
    }
    if ( ( p = strstr(strrev(stations), seq1) ) && strstr( p + strlen( seq1 ), seq2) )  {
      b = 1;
    }
    

    Also the array stations could be declared with the storage class specifier static

    static char stations[100003];
    

    And it will be more safer to write

    scanf("%100002s", stations);
    scanf("%102s", seq1);
    scanf("%102s", seq2);