函数错误指针运行时错误?

时间:2015-12-06 19:31:30

标签: c++ pointers

我正在尝试实现搜索两个C风格字符串之间匹配的函数,作为"编程:使用C ++的原则和实践"

但是,我得到一个运行时未处理的异常

Access violation reading location 0x008ff000. 

在坏指针值处断开(在代码中指示)。

#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();
}

为什么指针char* i未初始化为s_begin?我做错了什么?

1 个答案:

答案 0 :(得分:4)

您的循环条件错误。你拥有的是一个无限循环:

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

由于s_begin永远不会等于s_end i,所以最终会在字符串之外递增。将其更改为:

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