c - Function to search for string in array of strings -


i trying write function searches unique part(maximum 2 characters) of string in array of strings. although strstr , strchr not working , crash program reason. have resorted trying create resembles function.

my question this:
why strstr not working (something strstr(lex[j],word)) , doing wrong here?

here code function searches 2 unique characters within array of strings :

void convert(char word[]) {     int i;      (i = 0 ; <= strlen(word) ; i++)     {         if(word[i] >= 65 && word[i] <= 90)         {             word[i] = word[i]+32;         }     } }   int  twochar(char lex[50][50],char word[], int size,char temp[3]) {     int i,j,k,count,totlen;     convert(word);      (i = 0 ; < strlen(word) - 1 ; i++)     {         count = 0;         totlen = 0;         for(j = 0; j<size; j++)         {             convert(lex[j]);             totlen += strlen(lex[j]) - 1;             for(k = 0 ; k < strlen(lex[j]) - 1 ; k++)             {                 if (word[i] != lex[j][k] || word[i+1] != lex[j][k + 1])                 {                     count++;                 }             }         }         if(count =  = totlen)         {             temp[0] = word[i];             temp[1] = word[i+1];         }     } }    int main(int argc, char *argv[]) {     char lex[50][50] =  {"word1","word2","word3","word4" }, word[] = "test";     char p[3];      twochar(lex,word,4,p);     printf("%c%c\n",p[0],p[1]);     return 0; } 

this line:

for(k=0;k<strlen(lex[j])-1;k++) 

is problem.

strlen(lex[0]) 0 strlen(lex[0])-1 -1 (0xffffffff in 32 bit system) k starts @ 0 , incremented until equal 0xffffffff 

of course, k exceeds bounds of lex[0] when k = 50.

the result undefined behaviour leads seg fault event

to determine above, compiled/linked program via gcc, -ggdb parameter.

then ran program via 'gdb theprogram'

within gdb entered br main <-- break point set run c <-- continue program crashed seg fault event entered bt  <-- trace bt showed me line: 'if(word[i]!=lex[j][k] || word[i+1]!=lex[j] [k+1])' entered p k <-- print variable k =6832   (which way out of bounds)  entered run y br theprogram.c:41    (the line number above) <-- set break epoint c program stopped @ line 41 p j =0  ( gdb response ) p k  = 0 p = 0  little thinking,  stepping though inner loop using 'n' <-- next , playing on gdb  indicated problem in line 42 , resulted in revealing root of problem 

Comments

Popular posts from this blog

java - Custom OutputStreamAppender not run: LOGBACK: No context given for <MYAPPENDER> -

java - UML - How would you draw a try catch in a sequence diagram? -

c++ - No viable overloaded operator for references a map -