Ziezi
Ziezi

Reputation: 6477

Function Bad pointer runtime error?

I am trying to implement function that searches for match between two C-style strings, as a part of an exercise from "Programming: Principles and Practice using C++".

However, I am getting a runtime unhandled exception:

Access violation reading location 0x008ff000. 

that breaks at a bad pointer value (indicated in the code).

#include <iostream>

char* find (char* s, char* x) { 
    // variable that stores the first char of matching substring of s
    char* match = nullptr;

    // control variable indicating full match between x and substring of s
    bool full_match = false;

    if (s == nullptr || x  == nullptr) return match;

    size_t len_s = my_strlen(s);
    size_t len_x = my_strlen(x); 

    // x must be shorter than s
    if (len_s < len_x) return match;

    // pointers to beginning and end of s and x, used for traversal loops
    char *s_begin = s;
    char *s_end = s + len_s;

    char *x_begin = x;
    char *x_end = x + len_x;

    // traverse s 
    for (char* i = s_begin; s_begin != s_end; ++i) {

        // test for match between s and the first char of x
        if (*i == *x_begin) {
//-----------^  
// Code breaks here. Hovering above shows: 0x008ff000 <Bad Ptr>

            // assign s's matching char
            match = i;

            // if x's lenght is 1 return match
            if (len_x == 1) return match;

            // define new pointer to the next element of s
            char *i_next = i + 1;

            // traverse the rest of x 
            for (char* j = x_begin + 1; j != x_end; ++j) {

               // if there is even one mismatch brake loop and continue traversing s       
               if (*i_next != *j) break;

               // if the rest of x matches the rest of s, switch to full_match
               else if (j == x_end - 1) full_match = true;

               // increment x
               ++i_next;
            }
        // when x traversed and there is full_match, return the first matching char
        if (full_match) return match;
    }
}
// return nullptr to indicate no match
return nullptr;
}

//====================================================
int main () {
try {
    char* source = "abcde\0";
    char* target = "c\0";

    char *match_found = find(source, target);

    if(match_found) std::cout << *match_found << '\n';

} catch (std::exception &e) {
    std::cerr << e.what() << std::endl;
    getchar();
}
getchar();
}

Why is the pointer char* i not initialized to s_begin? What am I doing wrong?

Upvotes: 0

Views: 92

Answers (1)

Kevin
Kevin

Reputation: 7334

Your loop condition is wrong. What you have is an infinite loop:

for (char* i = s_begin; s_begin != s_end; ++i)

Since s_begin will never equal s_end i ends up incrementing outside of the string. Change it to:

for (char* i = s_begin; i != s_end; ++i)

Upvotes: 4

Related Questions