首页 > 解决方案 > 为什么越界访问不会在我的代码中产生任何错误?

问题描述

这是我的功能,我使用-std=c++17 -Wall -Wextrawithclanggccon运行godbolt

两个编译器都没有产生任何错误;

空针时函数返回0-1找不到针时返回,匹配时返回第index一次出现。

int strStr(string haystack, string needle) {

        if ( needle.empty( ) ) return 0;

        std::size_t n_len = needle.size();

        if( needle.size() > haystack.size() ) return -1;

        int index = 0;

        for ( auto it = haystack.begin(); it != haystack.end(); ++it )
        { 

            std::cout << std::string( it, it + n_len ) << std::endl; 
            if ( std::string( it, it + n_len ) == needle ) return index; // hear also
            //if ( !*(it + n_len ) ) break;
            index++;
        }

        return -1;

    }

我知道我可以使用findor得到结果substr

我已经在下面进行了测试,当我越界访问时它应该会产生错误,但没有错误;

int main()
{
    
    std::cout << strStr( "aabaaaababaababaa", "bbbb") << std::endl; // prints -1
    std::cout << strStr( "hello", "ll") << std::endl; // prints 2
    std::cout << strStr( "mississippi", "issip") << std::endl; // prints 4
    std::cout << strStr( "ab", "a") << std::endl; // prints 0
}

感谢您的时间和帮助;

标签: c++iterator

解决方案


当我越界访问时,它应该会产生错误

不。

越界访问数组的行为是未定义的。不能保证您会收到错误。

但是我已经测试了相同的代码leetcode平台,它产生了运行时错误

也不能保证您不会收到错误。没有任何保证。


推荐阅读