【问题标题】:Segmentation Fault - Invalid read of size 8分段错误 - 大小为 8 的无效读取
【发布时间】:2012-01-29 21:51:44
【问题描述】:

由于某种原因,以下 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;

但我看不出这条线有什么问题。那么这段代码有什么问题呢?

【问题讨论】:

  • 你的向量是空的。你可以使用 push_back() 来填充它。

标签: c++ string vector segmentation-fault


【解决方案1】:

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

vector<string> stringTable(256);

【讨论】:

    猜你喜欢
    • 2015-07-06
    • 2015-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多