I am getting a segmentation fault on this piece of code: void file_parser::check
ID: 3550816 • Letter: I
Question
I am getting a segmentation fault on this piece of code:
void file_parser::check_quote(vector<string> tokens)
{
bool has_quote;
vector<string> v1;
string tmpstr;
int FirstQuote;
int SecondQuote;
string tmp;
string tmpstr2;
for (int i = 0; i <= tokens.size(); i++) {
tmp = tokens[i].c_str();
for (int i = 0; i <= tokens.size(); i++) {
if (tmp[i] == ''') {
has_quote = true;
FirstQuote = i;
}
if (has_quote && i != FirstQuote && tmp[i] == ''') {
SecondQuote = i;
for (int k = FirstQuote; k <= SecondQuote; k++) {
tmpstr += tokens[k];
}
tokens.insert(tokens.begin() + FirstQuote, tmpstr);
for (int j = FirstQuote + 1; j < i; j++) {
for (int l = SecondQuote + 1; l <= tokens.size() - 1; l++) {
tmpstr2 = tokens[SecondQuote + 1];
tokens.insert(tokens.begin() + j, tmpstr2);
}
}
int test = tokens.size() - SecondQuote + 1;
while (test > 0) {
tokens.erase(tokens.end());
}
}
}
}
}
Explanation / Answer
You are running the for loop at each iteration for i=0 to i=tokens.size(). Run it till tokens.size()-1. It is trying to access an element which is not present.
Also all your loops have the same variable 'i' . Nested loops can lead to problems in such a scenario
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.