LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   c programming :searching a sub string in a string (http://www.linuxquestions.org/questions/programming-9/c-programming-searching-a-sub-string-in-a-string-4175448932/)

batman4 02-06-2013 04:30 PM

c programming :searching a sub string in a string
 
I was studying this code and got a segmentation fault .Please help me with this ..
Code:

#include<stdio.h>
#include<string.h>
int search(char[],char[]);

int main()
{
char a[100],b[40];
int loc;

printf("n Enter the main string :");
gets(a);

printf("n Enter the search string :");
gets(b);

loc = search(a,b);

if(loc==-1)
      printf("nNot found");
else
      printf("nFound at location %d",loc+1);

return(0);
}

int search(char a[],char b[])
{
int i,j,firstOcc;
i=0,j=0;

while(a[i]!='')
  {
    while(a[i]!=b[0] && a[i]!='')
        i++;
    if(a[i]=='')
        return(-1);    //search can not continue

    firstOcc = i;

    while(a[i]==b[j] && a[i]!='' && b[j]!='')
        {
        i++;
        j++;
        }

    if(b[j]=='')
        return(firstOcc);
    if(a[i]=='')
        return(-1);

    i = firstOcc + 1;
    j = 0;
  }
}


mina86 02-06-2013 05:18 PM

Never use gets().

Quote:

while(a[i]!='')
This is not valid C. You probably meant while (a[i]). The same applies for the rest of the code.

Quote:

while(a[i]==b[j] && a[i]!='' && b[j]!='')
If a[i]==b[j] and a[i]!=0 (since that's what you meant), than there's no need to check b[j].

Compile your program with gcc -ggdb and than run it through gdb:
Code:

$ gcc -ggdb -o example example.c
$ gdb
(gdb) file example
(gdb) run

PS. Never use gets().

johnsfine 02-06-2013 06:26 PM

Quote:

Originally Posted by mina86 (Post 4885819)
This is not valid C. You probably meant while (a[i]). The same applies for the rest of the code.

I'm sure the OP meant '\0' instead of ''. In a true/false test a[i] is true/false the same as a[i]!='\0' so your suggestion of removing the !='' would work as well as the clearer alternative of add the \0

Since the code wouldn't even compile, the reported seg fault is hard to explain.

With correct input the program adjusted just enough to compile then works correctly and does not seg fault.

Rather than just tell someone never use gets() it is better to explain that when the input is longer than the buffer, gets() will corrupt memory with almost any result possible, including seg fault. Then the beginner writing the code can decide whether input longer than buffer is a condition he chooses to worry about.


All times are GMT -5. The time now is 02:20 AM.