c++ - libc++abi.dylib:以 std::out_of_range 类型的未捕获异常终止:basic_string 错误?

标签 c++

这是我正在编写的一个函数,它接收一串由空格分隔的单词,并将每个单词添加到一个数组中。我不断收到一条错误消息,提示“libc++abi.dylib:以 std::out_of_range 类型的未捕获异常终止:basic_string”。我似乎找不到错误是什么。

void lineParser(string line, string words[])
{
    string word = "";
    int array_index = 0;
    int number_of_words = 1;
    int string_index = 0;
    while (string_index < line.length())
    {
        if (line.substr(string_index,1) != " ")
        {
            int j = string_index;
            while (line.substr(j,1) != " ")
            {
                word += line.substr(j,1);
                j++;
            }
            words[array_index] = word;
            array_index++;
            word = "";
            number_of_words++;
            string_index = j;
        }
        else
        {
            string_index++;
        }
    }
}

最佳答案

您的变量 j 也可以在没有边界检查的情况下增加。它最终会超过您将其用作 (.line.substr(j,1)) 的索引的字符串的长度。

一个非常糟糕的答案是在搜索 ' ' 字符之前在字符串 line 的末尾添加一个空格。一个更好的答案是在调用任何使用它作为索引访问字符串中的字符的函数之前,根据字符串的长度检查 j。

关于c++ - libc++abi.dylib:以 std::out_of_range 类型的未捕获异常终止:basic_string 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36962012/

相关文章:

c++ - 我可以将 VS C++ 项目生成的 DLL/EXE 工件存储在 NuGet 包中吗?

c++ - C++ 中 JSON 的 TinyXML 等价物?

C++ 检查是否为 Windows 10

c++ - 类型删除的 std::function 与虚函数调用的开销

c++ - Cocos2d C++ 等效于 objective-c 函数 CCCallBlock actionWithBlock

C++11 - 编译时多态性解决方案

c++ - 使用 boost multiprecision/mpfr float - string could not be interpreted as valid integer 错误

c++ - 如何加速一个简单的方法(最好不改变接口(interface)或数据结构)?

c++ - 为什么 c++17 的 emplace() 函数没有引用资格?

c++ - boost.log 含义和作用