Search code examples
cscanffgets

Error while using fgets in C


I'm writing a small program to check how the function strcasestr works.

What the code below does:

  1. Asks the user to enter a line of text.
    Example first input: blah bla blah blah the Word we are looking for. Example second input: Word

  2. What the program should print is: Word we are looking for.

  3. But it gives me a Segmentation fault (core dumped) error.

I suspect I'm using fgets() incorrectly. When I run the program using scanf to read the input (of course entering the first input withoutspaces) it works and gives me the expected output.

Any idea what's causing the segmentation fault error? How to correct this?

#define _GNU_SOURCE
#define max_buff 1000
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
char *answer;
//char * strcasestr (const char *haystack, const char *needle);

void strip_crlf(char* s);

void strip_crlf(char* s)
{
    char* p = strpbrk(s, "\r\n");
    if (p) *p = '\0';
}

int main(){
  char fname[max_buff+1];
  char lname[max_buff+1];

  printf("Enter the line of text you are searching for ");
  //scanf("%s", fname);

  fgets(fname,max_buff,stdin);
  //printf("%s",fname);
  strip_crlf(fname);

  printf("Enter the search term ");
  //scanf("%s", lname);
  fgets(lname,max_buff,stdin);
  strip_crlf(lname);
  //printf("%s",lname);
  if((answer=strcasestr(fname,lname))!=NULL){

  // printf("now we have something in answer ");
    printf("%s\n",answer);
  }
  else
      printf(" strcasestr failed\n");

}

EDITED: to reflect suggestions made in comments/answers below. the program now prints:

 strcasestr failed

...Ughh.

Edit2: program works now. thanks for all your help everyone!


Solution

  • You're not checking for a failure from strcasestr(), which IS failing, because you're not stripping \n or \r\n from your inputs.

    The only search that will succeed is if it matches the end of the first input.

    To strip CRLF:

    void strip_crlf(char* s)
    {
        char* p = strpbrk(s, "\r\n");
        if (p) *p = '\0';
    }
    

    Then just strip_crlf(fname); after fgets. Same for lname.