Ashish Rawat
Ashish Rawat

Reputation: 3513

Find substring in a string

Here is my code to find substring entered by the user in the 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, then return true, else false

int main(void) {
  printf("%d", find_str("ABCDEF", "CDE"));  /* Return true in this case */
  printf("%d", find_str("ABCDE", "CDE")); /* Return false in this case */

}

As explained in the comment, it returns true whenever it ends with an additional characters. If it is not, then it returns false. I think there is a problem in increment/decrement operator. But I could not find how?

Upvotes: 2

Views: 371

Answers (2)

asio_guy
asio_guy

Reputation: 3767

I analysed you piece of code a little bit and based on my analysis, I think the problem is in here

        while((*str++ == *++a));    /*empty*/

perhaps you would like to add another statement like below

while((*str++ == *++a) && ( *a != '\0' ) ) ;    /*empty*/

I guess you are missing a null check, what if both pointer are pointing to NULL termination they will still go forward that's exactly whats happening

I was going through your piece of code and found quite a few interesting things

  1. Lets say the memory allocated for CDE is at X
  2. say again the memory allocated for ABCDEF is at X+4 (this was the case in my machine)
  3. and say memory block allocated for ABCDE is at some X+Y or what ever

now when the function is called second time both pointers a and str point to respective memory locations starting at X+2 where Character C satisfies the condition above, however the condition will still be true even if they reach to end i.e at X+3 and hence a will move forward and point to A which makes your program behave erroneously

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727077

This is because your code decides to stop on finding \0 only after performing the comparison

*str++ == *++a

This condition will be true even when the match happens at the end of the string on null terminators, so the while loop would happily proceed beyond the end of both strings past the null terminator, causing undefined behavior.

Changing the condition to exit when *a is zero should fix the problem:

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

Upvotes: 4

Related Questions