代碼如下:
class SpeehManager { public: vector<vector<int>> vec; SpeechManager{ vector<int> v1; vector<int> v2; vector<int> v3; this->vec.push_back(v1); this->vec.push_back(v2); this->vec.push_back(v3); } void init() { //嘗試初始化v3容器 vector<vector<int>>::iterator it = this->vec.end(); (*it).push_back(1); (*it).push_back(2); (*it).push_back(3); (*it).push_back(4); (*it).push_back(5); } };
編譯出錯:
terminate called after throwing an instance of 'std::bad_alloc'what(): std::bad_alloc
分析解決:
【內存不夠】:
1,確認系統已占用內存是否正常,排除數據量過大導致的問題,此時系統內存不足導致 std::bad_alloc
【內存剩余】:
1,確認接口調用時,調用和背調接口的的參數是否一致,動態庫庫調用中若不一致,編譯鏈接通過,但執行可能導致 std::bad_alloc
2,確認是否使用vector,vector超容量時會重新申請二倍內存,因為vector會將老的一塊內存,完全拷貝到另一塊連續容量為2倍的vector內存中,高峰時內存將時當前系統的3倍,此時可能導致 std::bad_alloc
仔細看了下寫的代碼,想到一個知識點:vector容器的end指向的並不是容器中最后一個元素,而是最后一個元素的下一個元素地址,所以訪問了非法內存,故這里的解決方法是:如果要訪問容器中最后一個元素,需要將迭代器--,即it--。
參考鏈接:https://blog.csdn.net/wuhenlegou110/article/details/86743672