带有空集的"超出绑定的迭代器"

Ara*_*san 1 c++ iterator set segmentation-fault c++17

我在这段代码中遇到了分段错误:

#include <iostream>
#include <set>

int main() {
    std::set<int> st;
    auto rf = --st.end();
    std::cout << "Size of the set is: " << (int) st.size() << std::endl;

    if ( (int) st.size() > 0) { // size of st is zero here
        int foo = (*rf);  // rf is out bound
        std::cout << "foo: " << foo << std::endl;
    }
}
Run Code Online (Sandbox Code Playgroud)

由于st是空的,所以if条件永远不会成立,无论rf是否出界.如果我注释掉if块,那么程序运行正常.

我也尝试了它std::vector也运行良好.

为什么我会出现分段错误?为什么"如果带有无效语句的条件总是假的"会影响代码的运行?

编译:

g++ -Wall -Wextra -Wshadow -Wfloat-equal -pedantic -std=c++17 -Wconversion -lm test.cpp
Run Code Online (Sandbox Code Playgroud)

YSC*_*YSC 12

这是未定义的行为:

std::set<int> st;
auto rf = --st.end();
Run Code Online (Sandbox Code Playgroud)

因为st是空的,st.begin() == st.end()并且递减这两个(和相同的)迭代器中的任何一个是不正确的.

我也尝试过矢量并运行良好.

这是UB最有害的结果之一:它可能看起来没问题.它不是.