c - Find substring in a string -


here code find substring entered user in given string.

bool find_str(char *str, char const *substr) {     while(*str) {         if(*str++ == *substr) {             char const *a = substr;             while((*str++ == *++a));  /*empty*/             if(*a == '\0')                 return true;         }     }     return false; } // if match found, return true, else false  int main(void) {   printf("%d", find_str("abcdef", "cde"));  /* return true in case */   printf("%d", find_str("abcde", "cde")); /* return false in case */  } 

as explained in comment, returns true whenever ends additional characters. if not, returns false. think there problem in increment/decrement operator. not find how?

this because code decides stop on finding \0 after performing comparison

*str++ == *++a 

this condition true when match happens @ end of string on null terminators, while loop happily proceed beyond end of both strings past null terminator, causing undefined behavior.

changing condition exit when *a 0 should fix problem:

while((*str++ == *++a) && (*a)); 

Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -