分段故障-大小为8的读取无效

Segmentation Fault - Invalid read of size 8

本文关键字:读取 无效 小为 故障 分段      更新时间:2023-10-16

由于某些原因,以下C++代码导致分段错误:

#include <sstream>
#include <vector>
using namespace std;
string charToString(char c)
{
    stringstream ss;
    string s;
    ss << c;
    ss >> s;
    return s;
}
int main()
{
    vector<string> stringTable;
    for(int c = 0; c < 256; ++c){
        string s = charToString(c);
        stringTable[c] = s;
    }
}

Valgrind在线上报告错误Invalid read of size 8

stringTable[c] = s;

但我看不出这行有什么毛病。那么这个代码出了什么问题?

您正在注销vector的末尾。使用给vector一个初始大小

vector<string> stringTable(256);