![](/img/trans.png)
[英]string c++ : libc++abi.dylib: terminating with uncaught exception of type std::out_of_range: basic_string
[英]libc++abi.dylib: terminating with uncaught exception of type std::out_of_range: basic_string Error?
這是我正在編寫的函數,該函數接收由空格分隔的單詞字符串,並將每個單詞添加到數組中。 我不斷收到一條錯誤消息,指出“ 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++;
}
}
}
訪問words
時,沒有數組邊界檢查。 如果傳入的數組沒有分配足夠的空間,則將運行到數組末尾。
正如您在下面指出的那樣,這不一定是問題,但是如果不看其余的代碼(例如,主代碼)就不可能說出來。 這也是非常糟糕的代碼,永遠不要僅僅假設自己知道數組的長度。 您正在使用C ++,請使用STL容器。 它將為您節省與陣列相關的難以置信的麻煩。
您的變量j
也可以在沒有邊界檢查的情況下增加。 最終,它將超出您將其用作( .line.substr(j,1)
)的索引的字符串的長度。
一個非常糟糕的答案是在搜索' '
字符之前在字符串line
的末尾添加一個空格。 更好的答案是在調用任何使用它作為索引訪問字符串中字符的函數之前,先對j的字符串長度進行檢查。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.