For some reason the following C++ code results in a segmentation fault:
#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 reports the error Invalid read of size 8 on the line
stringTable[c] = s;
But I can’t see what’s wrong with this line. So what is wrong with this code?
You’re writing off the end of the
vector. Give thevectoran initial size with