Segmentation Fault段错误

遇见的场景

在刷Leetcdoe题的时候,测试用例报错

runtime error: applying non-zero offset 18446744073709551612 to null pointer (stl_iterator.h)

在本地vscode调试时报的错是segmentation fault。

仔细观察发现是这段代码的问题:在使用ans.begin() + 1的时候没有判断ans是否为空;

如果容器ans是空的(ans.empty() = true),那么ans.begin()与ans.end()相同,都是空指针,即不能apply non-zero offset to null pointer。

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

      if(*it == *(it - 1)){

        auto ita = it;

        ans.erase(ita);

      }else{

        it++;

      }

    }

所以在使用这些容器之间一定要判断是否为空。

ans.empty()

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容