Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I keep recieving a Segmentation fault (core dumped) when I run the c program. Wh

ID: 3709193 • Letter: I

Question

I keep recieving a Segmentation fault (core dumped) when I run the c program. What is causing the issue and how can I fix it?

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

int main()
{
       FILE *fpt = fopen("test.txt", "r");
    char str1[15], str2[15];
       int read;

    printf("Enter the search string: ");
   fgets(str1, 15, fpt);

    while(fscanf(fpt, "%15s", str2) == 1)
    {
       read = strlen(str2);
              if(strncmp(str1, str2, read)==0)
              {
                    printf("Found: %s", str2);
              }
    }
    fclose(fpt);
    fgets(str1, 15, fpt);
}

Explanation / Answer

The segmentataion error is due to the length of string str1[15], str2[15];

if the scanned length of string is greater than 15, we may get the segmentataion error

one solution is set the length of str1 and str2 from 15 to a greater index value say 150

  char str1[150], str2[150]; instead of   char str1[15], str2[15]; should do the trick