Home > Mobile >  How to fix segmentation error in C programming?
How to fix segmentation error in C programming?

Time:10-19

I want to get the user input to open a txt file but I'm getting this compilation error called. [1] 85501 segmentation fault can someone help me with this? A sample input 2021-10-17

Here's git repo https://github.com/anjula-sack/diary

    void DecryptEntry()
    {
      FILE *fptr;

      char filename[20];
      printf("Please enter the date of the entry you want to read, ex:2021-10-17\n");
      fscanf(stdin, " ");
      fgets(filename, 20, stdin);
    
      strcpy(filename, ".txt");
      printf("%s.txt", filename);
    
    
      if ((fptr = fopen(filename, "r")) == NULL)
      {
        printf("Error! the entry doesn't exist");
      }
    }

CodePudding user response:

Looking at the actual code from your github link, then you have this:

strcpy(filename, ".txt");

if ((fptr = fopen(filename, "r")) == NULL)
{
  printf("Error! the entry doesn't exist");
}

fgets(message, 100, fptr);

First of all the strcpy is nonsense since it overwrites the filename and replaces it with ".txt". Since that is never a valid file name, fopen will always fail. And when it fails, you print an error message but continue execution, so the next fgets call will cause the crash.

Fix this by allocating enough space for filename, replace strcpy (overwrite) with strcat (append) and do a return etc upon failing to open the file.

You could easily have found these bugs yourself by single-stepping through the function using a debugger.

  • Related