c++ - 为什么越界访问不会在我的代码中产生任何错误?
问题描述
这是我的功能,我使用-std=c++17 -Wall -Wextra
withclang
和gcc
on运行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;
}
我知道我可以使用find
or得到结果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
}
感谢您的时间和帮助;
解决方案
当我越界访问时,它应该会产生错误
不。
越界访问数组的行为是未定义的。不能保证您会收到错误。
但是我已经测试了相同的代码leetcode平台,它产生了运行时错误
也不能保证您不会收到错误。没有任何保证。
推荐阅读
- r - R:在所有可能的变量组合之间执行 Cohen 的 Kappa 检验
- python - 以python方式整理列表推导
- c# - Unity 文件名与类名错误不匹配 - 但它们确实匹配
- flutter - Flutter:Future函数不断调用
- r - Group_by / summarise 语句不适用于多个语句
- azure - Azure MSI 强制令牌刷新
- angular - 使用 Angular 和 nginx 我收到错误 Uncaught TypeError: Super expression must be null or a function
- azure-cosmosdb - Gremlin 查询以在同一响应中检索计数和数据
- c# - C# MySQL 无法连接到 ubuntu 服务器
- wordpress - 如何在 WooCommerce 中向用户提供运输方式选择?